2013-04-06 50 views
1

我的印象是,孩子類繼承父母的屬性。然而,下面,在B類中輸出爲null ......有人能告訴我如何從父類訪問屬性嗎?定義在PHP中,我們如何獲得父類變量?

$aClass = new A(); 
$aClass->init(); 

class A { 

    function init() 
    { 
     $this->something = 'thing'; 
     echo $this->something; // thing 
     $bClass = new B(); 
     $bClass->init(); 
    } 

} 

class B extends A { 

    function init() 
    { 
     echo $this->something; // null - why isn't it "thing"? 
    } 
} 
+2

您已經定義了類A兩次,而類B沒有......你確定這段代碼是正確的嗎? – Mchl 2013-04-06 18:21:20

+0

你的意思是'B類延伸A'嗎? – Sam 2013-04-06 18:22:42

+0

SOrry,這是一個錯字,我糾正了它...... – Andrew 2013-04-07 09:17:53

回答

4

有在你的代碼的幾個錯誤。我糾正了他們。以下腳本應按預期工作。我希望代碼的意見是有幫助的:

class A { 

    // even if it is not required you should declare class members 
    protected $something; 

    function init() 
    { 
     $this->something = 'thing'; 
     echo 'A::init(): ' . $this->something; // thing 
    } 

} 

// B extends A, not A extends B 
class B extends A { 

    function init() 
    { 
     // call parent method to initialize $something 
     // otherwise init() would just being overwritten 
     parent::init(); 
     echo 'B::init() ' . $this->something; // "thing" 
    } 
} 


// use class after(!) definition 
$aClass = new B(); // initialize an instance of B (not A) 
$aClass->init(); 
+3

這會耗盡內存,因爲B會被不定地實例化 – 2013-04-06 18:28:54

+0

不,爲什麼要這樣呢? – Sven 2013-04-06 18:30:42

+0

@ dev-null-dweller感謝您的提示!我沒有看起來如此接近init函數,並監督這個 – hek2mgl 2013-04-06 18:33:07

1

你的第二類應該是class B extends A,而不是class A extends B

+0

即使那樣,這也不是一個解決方案。他會重寫init()方法,以便父類中的一個永遠不會被調用。 – Mchl 2013-04-06 18:22:17

+0

對。他必須在B類的'init'函數中調用'parent :: init()'。 – xbonez 2013-04-06 18:23:03

+0

@xbonez - 當調用init時,我只能訪問該函數中定義的變量嗎? – Andrew 2013-04-07 09:19:06

0

我們訪問使用以下語法在PHP父類成員:

parent::$variableName

或者

parent::methodName(arg, list)