2010-11-07 189 views
6

嗨我有一個關於$ this的問題。php類擴展

class foo { 

    function __construct(){ 

     $this->foo = 'bar'; 

    } 

} 

class bar extends foo { 

    function __construct() { 

     $this->bar = $this->foo; 

    } 

} 

$ob = new foo(); 
$ob = new bar(); 
echo $ob->bar; 

結果bar ??

我只問,因爲我認爲它會,但除了我的腳本似乎並沒有導致我的想法。

回答

10

引述PHP manual

注:父構造函數則不會暗中調用如果子類定義了一個構造函數。爲了運行父構造函數,需要在子構造函數中調用parent :: __ construct()

這意味着,在你的榜樣,當bar運行的構造函數,它不運行的foo構造,所以$this->foo仍然是不確定的。

5

PHP是有點奇怪,因爲parent constructor is not automatically called if you define a child constructor - 你必須自己調用它。因此,要獲得您想要的行爲,請執行此操作:

​​
+0

有點奇怪,但很靈活,因爲你可以很容易地根本過載(只調用父) ,部分重載構造函數(從新構造函數中調用它)或完全重載​​它(根本不調用它)。所以雖然與其他語言相比很奇怪,但這並不意味着它很奇怪(它可以被看作是一個巨大的好處)... – ircmaxell 2010-11-07 15:39:51

+0

那麼這個擴展類被稱爲是沒有意義的嗎?我認爲這會帶來它的對象。 – 2010-11-07 18:30:04

+0

不,$ this繼續引用當前實例 – 2010-11-07 20:08:56

0

您不會創建foo和bar的實例。創建一個條的單個實例。

$ob = new bar(); 
echo $ob->bar; 

和其他答案已經指出的那樣,調用父:: __結構()你的酒吧構造函數中