2011-05-25 83 views
2

我有腦膜炎,我懷疑這個很簡單。 考慮以下代碼,有兩個類:爲什麼我的PHP子類沒有從父類獲得公共和受保護的變量?

<?php  
class myparentclass { 
    protected $vara; 
    private $varb; 
    public $varc; 
    public $_childclass; 

    function __construct() { 
     $this->vara = "foo"; 
     $this->varb = "bar"; 
     $this->varc = ":("; 
     $this->_childclass = new mychildclass;  
    } 
} 

class mychildclass extends myparentclass { 
    function __construct() { 
     print_r ($this); 
    } 
} 

print "<pre>"; 
$foo = new myparentclass(); 

輸出是:

mychildclass Object 
(
    [vara:protected] => 
    [varb:private] => 
    [varc] => 
    [_childclass] => 
) 

我知道$ varb不應設置,但對於其他人呢?

+0

告訴你這很簡單! +1全部,謝謝。 – 2011-05-25 13:23:56

回答

4

如果在子類中定義一個新__construct()因爲你對我所做的打印瓦爾出來,你需要顯式調用父類的構造了。如果你沒有在子類中定義任何__construct(),它將直接繼承父類,並且所有這些屬性都將被設置。

class mychildclass extends myparentclass { 
    function __construct() { 
    // The parent constructor 
    parent::__construct(); 
    print_r ($this); 
    } 
} 
2

你必須調用子類構造函數內的父類構造函數。

function __construct() { 
     parent::__construct(); 
     print_r ($this); 
    } 
1

如果子類有它自己的構造函數,你必須顯式調用從內它的父類的構造(如果你想叫):

parent::__construct(); 
2

如果在重新定義構造您子類,你必須調用父構造函數。

class mychildclass extends myparentclass { 
function __construct() { 
    parent::__construct(); 
    print_r ($this); 
} 
} 

應該正常工作。

1

您的父構造函數永遠不會被孩子執行。像這樣修改mychildclass:

function __construct() { 
    parent::__construct(); 
    print_r ($this); 
} 
1

您正在用父類中的構造函數重寫父類的構造方法。您可以使用parent :: __ construct()從父類的構造函數中調用父類的構造函數。

然而,myparentclass的構造函數的最後一行調用mychildclass的構造函數,後者又調用父構造函數等等。你的意思是達到這個目的嗎?

<?php  
class myparentclass { 
    protected $vara; 
    private $varb; 
    public $varc; 

    function __construct() { 
     $this->vara = "foo"; 
     $this->varb = "bar"; 
     $this->varc = ":("; 
    } 
} 

class mychildclass extends myparentclass { 
    function __construct() { 
     parent::__construct(); 
     print_r ($this); 
    } 
} 

print "<pre>"; 
$foo = new mychildclass(); 
相關問題