无法访问父 class 属性

Can't access parent class properties

当我使用父 class 属性时 returns 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,它不会 return NULL 更多

发生这种情况是因为应该显式调用父构造函数:

class Bar extends Foo
{
    public function __construct() {
        parent::__construct();
    }


    public function Some_method() {
        return $this->example_property; // Outputs NULL
    }
}

但仔细观察 - 如果您不声明 Bar 构造函数,则应该执行父构造函数。也许您没有向我们展示完整的代码?

因此,如果您在子 class 中有 __construct 并且想要使用父构造函数 - 您应该显式调用它,正如我所说的 parent::__construct();

如果子 class 中没有 __construct 方法,将调用父的方法。