继承的意义在于,我拥有你的,我还可以定义自己的
public $name; public $sex; public $iq=10; const BIRTHPLACE='地球'; //构造函数 public function __construct($name,$sex){ $this->name=$name; $this->sex=$sex; } public function eat($food){ echo "{$this->name}正在吃{$food}!
"; } } class Student extends Humanity { public $studentId; public function test($subject){ echo "{$this->name}正在考{$subject}!
"; } } class Worker extends Humanity { } class ClassLeader extends Student { public function manage($arg){ echo "{$this->name}:{$arg}"; } } $hanMM=new Student('韩梅梅','女'); $hanMM->eat('苹果'); $hanMM->test('数学'); $xiaoXin=new Worker('蜡笔小新','男'); $xiaoXin->eat('青椒'); $liLei=new ClassLeader('李雷','男'); $liLei->eat('香蕉'); $liLei->manage('你们上课不要乱说话,不要影响其他同学!');
解析:
//继承 1:我们在定义某个类的时候,可以指定这个类 根据 程序中已经存在的 某个类 派生而来! 2:Student类继承了Humanity这个类 3:Student称作是Humanity的子类,Humanity是Student的父类 4:子类继承了父类的属性(变量)和方法,就相当于,子类中有和父类一样的属性以及方法,就像是子类自己的一样! 5:子类可以再去定义属于自己的属性以及方法,类常量
public $name; public $sex; public $iq=10; const BIRTHPLACE='地球'; //构造函数 public function __construct($name,$sex){ $this->name=$name; $this->sex=$sex; } public function eat($food){ echo "{$this->name}正在吃{$food}!
"; } } class Student extends Humanity { public $studentId; public function test($subject){ echo "{$this->name}正在考{$subject}!
"; } //方法重写,相当于在当前这个子类里面覆盖了父类的某个方法! //参数的个数要和父类一致,构造函数的参数个数无需和父类里面的构造函数的参数个数一致 public function eat($food){ echo "{$this->name}正在快速的吃{$food}!
"; } } class Worker extends Humanity { } $hanMM=new Student('韩梅梅','女'); $hanMM->eat('苹果'); $xiaoXin=new Worker('蜡笔小新','男'); //对其他的子类没有影响 $xiaoXin->eat('青椒');
解析:
重写的核心在于,我可以在你的基础上,改成我的。比如我喜欢吃青椒不喜欢吃苹果
public $name; public $sex; public $iq=10; const BIRTHPLACE='地球'; //构造函数 public function __construct($name,$sex){ $this->name=$name; $this->sex=$sex; } //方法的前面加上final,这个方法就不能被子类 重写(覆盖) final public function eat($food){ echo "{$this->name}正在吃{$food}!
"; } } class Student extends Humanity { public $studentId; public function test($subject){ echo "{$this->name}正在考{$subject}!
"; } //方法重写,相当于在当前这个子类里面覆盖了父类的某个方法! //参数的个数要和父类一致,构造函数的参数个数无需和父类里面的构造函数的参数个数一致 //父类中被覆盖了的方法不会在执行 //如果你真的希望在子类里面访问被当前类覆盖了的父类中的方法怎么办呢? public function eat($food){ echo "{$this->name}正在快速的吃{$food}!
"; } } class Worker extends Humanity { } $hanMM=new Student('韩梅梅','女'); $hanMM->eat('苹果'); $xiaoXin=new Worker('蜡笔小新','男'); //对其他的子类没有影响 $xiaoXin->eat('青椒');
解析: 被final修饰的,被子类重写了报错了·