2013-07-02 57 views
1

我得到了Father類受保護的變量,這個變量的內容將在Father類改變,但我需要在子類來使用這個變量,即:爲什麼父類的受保護變量爲空?

class Father { 
    protected $body; 
    function __construct(){ 
     $this->body = 'test'; 
    } 
} 

class Child extends Father{ 
    function __construct(){ 
     echo $this->body; 
    } 
} 

$c = new Father(); 
$d = new Child(); 

爲什麼變量body來空的?如果我聲明它是靜態的,它應該工作,如果我想要在子類中訪問和修改這些變量,我應該聲明所有變量都是靜態的嗎?

回答

3

您必須調用父構造函數。

class Father { 
    protected $body; 
    function __construct(){ 
     $this->body = 'test'; 
    } 
} 

class Child extends Father { 
    function __construct(){ 
     parent::__construct(); 
     echo $this->body; 
    } 
} 

$c = new Father(); 
$d = new Child(); 

參考:http://php.net/manual/en/language.oop5.decon.php

+0

肯定,但如果我叫父母再建造它會再次運行相同的代碼,ins't? –

+0

你只需要兩次調用一個構造函數,你自己實際調用構造函數的唯一時間就是在子構造函數內部,就像這裏的情況一樣。 – luk2302

0

這是因爲你覆蓋的構造函數。您還必須調用父項的構造函數。 More info

class Child extends Father { 
    function __construct() { 
     parent::__construct(); 

     echo $this->body; 
    } 
} 
相關問題