我想完成以下任务,但我不确定如何做到:
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()
方法的情况下执行此操作,或者我是否必须创建一个新方法?
编辑:为了澄清,我不想在继承的方法中重述"do something",我只想在foo->doSomething()方法中声明一次,然后在子类中构建它。
你就这么做了。如果您想在foo
中调用doSomething()
,只需在bar
:中执行此操作即可
function doSomething() {
// do bar-specific things here
parent::doSomething();
// or here
}
而您提到的重新启动方法通常被称为重载。
您可以使用parent
关键字:
class bar extends foo {
function doSomething(){
parent::doSomething();
}
}
当扩展一个类时,您可以简单地使用$this->method()
来使用父方法,因为您没有覆盖它。当您覆盖它时,代码片段将指向新方法。然后您可以通过parent::method()
访问父方法。