2012-01-27 122 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()访问父级方法。