我有一个父母课,我将调用'ParentClass'和一个子类(从中延伸(,我将调用'ChildClass'。
-
ParentClass拥有$ prop1和$ prop2的保护,我希望ChildClass可以访问。但是我从他们那里得到了零。
-
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
}
}
如果子类从中延伸,为什么子类无法访问父类的属性?
它们是可访问的,但它们将是null
,因为它们未从孩子传递给父构建器:
(new ChildClass(1,2))->anotherFakeMethod();
沙盒
输出
NULL
在这种情况下,您的课程会产生null
的预期结果。好吧,它会根据其编码方式产生我期望的。
要修复它,您必须通过孩子的构造函数将数据传递回父级,或删除孩子的构造函数。这样:
class ChildClass extends ParentClass {
public function __construct($prop1, $prop2) {
parent::__construct($prop1, $prop2);
}
....
}
上述更改之后:
(new ChildClass(1,2))->anotherFakeMethod();
输出
int(1)
沙盒
这是我从这一行所期望的,因为它基本上是构造函数中使用的第一个参数:
var_dump($this->prop1);
,如果您知道他们在孩子课中的内容,也可以这样做:
public function __construct() {
parent::__construct(1, 2); //say I know what these are for this child
}
您当然可以在新的构造函数中手动设置它们,但这将是湿的(写两次(或不必要的重复,在这种情况下。
欢呼!