[英]PHP Access public variable changed in constrict from child class
如何访问父类使用__construct设置的子类中的公共属性?
例如:
class Parent
{
protected $pVariableParent = 'no info'; //This have to be set for all classes
public function __construct()
{
$this->setPVariable(); //Changing the property when class created.
}
public function setPVariable(){
$this->pVariableParent = '123';
}
}
Class Child extends Parent
{
public function __construct()
{
if(isset($_GET['info']){
echo $this->pVariableParent;
}
}
}
$pInit = new Parent;
$cInit = new Child;
在这种状态下,请求site.php/?info
显示no info
。 但是如果我调用$this->setPVariable();
来自Child,一切正常,并显示123
。 为什么我无法从父级访问已更改的属性? 是因为当我调用Child类时,它只读取所有父级的属性和方法,但不触发任何构造函数吗? 最好的方法是什么? 感谢名单。
问题是您覆盖了父构造函数,因此在子构造函数中未调用setPVariable
。
扩展父构造函数而不是重写:
Class Child extends Parent
{
public function __construct()
{
parent::__construct();
if(isset($_GET['info']){
echo $this->pVariableParent;
}
}
}
http://php.net/manual/it/keyword.parent.php
让我尝试澄清一点:
为什么我无法从父级访问已更改的属性?
因为该属性尚未更改。 您正在创建两个单独的对象; $pInit
是父类的实例,其属性值在构造函数中更改。 $cInit
是子类的实例,并且其属性值未更改,因为您覆盖了构造函数,并且子类不更改属性值。 $pInit
和$cInit
不相关(按类型除外),它们当然不会相互影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.