【发布时间】:2016-02-11 18:36:05
【问题描述】:
当我使用父类属性时,它返回NULL,我不知道为什么会这样,示例代码:
class Foo
{
public $example_property;
public function __construct(){
$this->example_property = $this->get_data();
}
public function get_data() {
return 22; // this is processed dynamically.
}
}
class Bar extends Foo
{
public function __construct(){}
public function Some_method() {
return $this->example_property; // Outputs NULL
}
}
实际上,当我使用constructor 设置属性值时会发生这种情况,但是如果我静态设置值(例如:public $example_property = 22,它将不再返回NULL
【问题讨论】:
-
这对我有用。你能用你用来获取该属性的代码编辑帖子吗?
-
我使用了@u_mulder 答案,它奏效了!
-
所以你的
Bar类中必须有一个__construct(),否则它会被继承。 -
是的,其实我有,是这个原因吗?
-
是的。如果没有显式调用,
parent::__construct()将被覆盖
标签: php inheritance visibility