PHP class 继承

王朝学院·作者佚名  2016-05-25
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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

<?phpclass 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<?phprequire_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=parentNamechild setAge() age=child setLocal() local=child localparent setHoby() hoby=parent hobyChild[name=, age=20, local=child local, hoby=parent hoby]Child[name=, age=20, local=child local, hoby=parent hoby]

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航