2015-11-10 203 views
1

当我使用它返回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发生,但如果我staticly设定值(例如:public $example_property = 22,它不会返回任何NULL

+1

这是为我工作。您能否使用您用来获取该财产的代码编辑帖子? – fpietka

+0

我用@u_mulder的答案,它的工作! – Amin

+1

所以你必须在'Bar'类中有'__construct()',否则它会被继承。 – fpietka

回答

3

这是因为父类的构造应明确要求:

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


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

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

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

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

+1

幸运的是没有必要。 – fpietka

+0

哦,谢谢@u_mulder,它实际上工作! – Amin

+1

扩展类继承构造函数。从你的例子,它应该马上工作 – fpietka