【问题标题】:Can't access parent class properties无法访问父类属性
【发布时间】: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


【解决方案1】:

这是因为应该显式调用父构造函数:

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


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

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

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

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

【讨论】:

  • 幸好不需要。
  • 扩展类继承构造函数。从您的示例来看,它应该立即起作用
  • 我不知道为什么会这样,但是在添加 parent::__construct() 之后它起作用了! o.O
  • 严格根据您的代码示例,$bar = new Bar(); echo $bar->Some_method(); 输出 22。 @u_mulder 更改了我的投票,请您修改。
猜你喜欢
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 2019-08-24
  • 2014-03-06
相关资源
最近更新 更多