可以';t访问父类属性


Can't access parent class properties

当我使用父类属性时,它会返回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

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

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

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

但仔细观察一下——如果您没有声明Bar构造函数,则应该执行父构造函数。也许你没有给我们看完整的代码?

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

如果子类中没有__construct方法,则会调用父类的方法。