如何访问由父母类设置的儿童类中的公共财产?
?例如:
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
。但是,如果我从Child打电话给$this->setPVariable();
,一切都可以正常工作并显示123
。为什么我无法访问父母已更改属性?是因为当我称呼儿童班时,它只是读取所有父母的属性和方法,但不会触发任何构造功能?最好的方法是什么?thanx。
问题是您覆盖了父构建体,因此在子构造函数中未调用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
无关(按类型除外(,它们当然不会影响彼此的内部结构。