PHP class 继承
1.执行结果
成员名 | 成员修饰符 | 方法名 | 方法修饰符 | 执行结果 |
name | private | setName | private | 在构造函数函数中执行父类私有方法,子类未能覆盖private成员变量和方法,修改父类的私有变量 |
age | private | setAge | public | 修饰符是public,子类方法覆盖父类方法,修改子类成员变量。但在父类构造其中执行$this->age只能取到父类的age |
local | public | setLocal | public | 子类的方法和成员变量均覆盖了父类对应方法和成员变量 |
hoby | public | setLocal | private | 成员变量被覆盖,当是方法未覆盖 |
2.相关代码
ParentClass.php
<?php class ParentClass { private $name; private $age; public $local; public $hoby; public function __construct() { print "execute parent construct()<br/>"; $this->setName (); echo ("name=" . $this->name . "<br/>"); $this->setAge (); echo ("age=" . $this->age . "<br/>"); $this->setLocal (); echo ("local=" . $this->local . "<br/>"); $this->setHoby (); echo ("hoby=" . $this->hoby . "<br/>"); $this->__toString(); } private function setName() { $this->name = "parentName"; print "parent setName()\n "; } public function setAge() { $this->age = 50; print "parent setAge()\n"; } public function setLocal() { $this->local = "parent local"; print "parent setLocal()\n"; } private function setHoby() { $this->hoby = "parent hoby"; print "parent setHoby()\n"; } public function __toString() { echo ("Parent[name=" . $this->name . ", age=" . $this->age . ", local=" . $this->local . ", hoby=" . $this->hoby . "]<br>"); } } ?>
ChildClass.php
<?php require_once 'ParentClass.php'; class ChildClass extends ParentClass { private $name; private $age; public $local; public $hoby; public function __construct() { print "execute child construct()<br/>"; parent::__construct (); echo $this->__toString(); } private function setName() { $this->name = "childName"; print "child setName()\n"; } public function setAge() { $this->age = 20; print "child setAge()\n"; } public function setLocal() { $this->local = "child local"; print "child setLocal()\n"; } private function setHoby() { $this->hoby = "child hoby"; print "child setHoby()\n"; } public function __toString() { echo ("Child[name=" . $this->name . ", age=" . $this->age . ", local=" . $this->local . ", hoby=" . $this->hoby . "]<br/>"); } } $child = new ChildClass (); ?>
3.执行输出
execute child construct()
execute parent construct()
parent setName() name=parentName
child setAge() age=
child setLocal() local=child local
parent setHoby() hoby=parent hoby
Child[name=, age=20, local=child local, hoby=parent hoby]
Child[name=, age=20, local=child local, hoby=parent hoby]