2015-11-10 197 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