我有一个父类,我将称之为“ParentClass”,还有一个子类(从它扩展而来),我将称之为“ChildClass”。
ParentClass 具有我希望 ChildClass 访问的受保护属性 $prop1 和 $prop2。但我从他们那里得到了 NULL。
ParentClass 有一个 __construct() 方法,它设置通过依赖注入接收的属性。
ParentClass 从其方法之一实例化 ChildClass。
ChildClass 覆盖父构造函数,但在其自己的 __construct() 方法中不包含任何代码。
我已经用 var_dump($this->prop1) 测试了父类的属性。它返回我期望的值。
但是,如果我从子类中 var_dump($this->prop1) ,我会得到 NULL。
class ParentClass {
protected $prop1;
protected $prop2;
public function __construct($prop1, $prop2) {
$this->prop1 = $prop1;
$this->prop2 = $prop2;
}
public function fakeMethod() {
$child = new ChildClass;
$child->anotherFakeMethod();
// logic
}
}
class ChildClass extends ParentClass {
public function __construct() {
// this overrides the parent constructor
}
public function anotherFakeMethod() {
$prop1 = $this->prop1;
$prop2 = $this->prop2;
var_dump($this->prop1);
// returns NULL
}
}
如果子类从父类扩展,为什么它不能访问父类的属性?
一只斗牛犬