2012-01-27 126 views
0

我要完成以下,但我不知道如何做到這一點:PHP類的繼承和擴展方法

class foo { 
    function doSomething(){ 
     // do something 
    } 
} 

class bar extends foo { 
    function doSomething(){ 
     // do something AND DO SOMETHING ELSE, but just for class bar objects 
    } 
} 

是否有可能做到這一點,同時仍然使用doSomething()方法,還是我必須創建一個新的方法?

編輯:爲了澄清,我不想在繼承的方法中重申'做些什麼',我只想在foo-> doSomething()方法中聲明一次,然後在子類中構建它。

回答

2

你做到了。如果你想調用doSomething()foo,簡單地做這bar

function doSomething() { 
    // do bar-specific things here 
    parent::doSomething(); 
    // or here 
} 

而且重申你提到的方法,通常被稱爲超載。

+0

這正是我所需要的;謝謝! – Matthew 2012-01-27 21:51:41

1

您可以使用關鍵字parent做到這一點:

class bar extends foo { 
    function doSomething(){ 
     parent::doSomething(); 
    } 
} 
0

當擴展一個類,你可以簡單地使用$this->method()使用父法,因爲你沒有覆蓋它。當你覆蓋它時,片段將指向新的方法。您可以通過parent::method()訪問父級方法。