是否可以有一个子函数调用同名的父抽象函数?换句话说,我希望父类的函数是抽象的,以便它强制每个子类实现它。但是,我不想完全覆盖父函数,我希望能够在子函数中调用它。像这样的东西:
class Parent {
abstract function doSomething() {
$do = true;
}
}
class Child extends Parent {
function doSomething() {
parent::doSomething(); // sets $do = true
$also_do = true;
}
}
抽象方法不能有主体
abstract function doSomething();
如果你想让它有一个主体,你一定不能声明它
abstract
。如果你想强制子类严格重写现有方法,那么你的设计就有问题,或者你应该引入另一种方法(例如abstract function doSomethingChildSpecific()
)。
但是,可以按照您已经执行的方式调用重写的方法。
在我看来,你在想,当程序员声明一个新的虚拟的、可重写的方法时,它是“抽象的”,而它不是。 “抽象方法”确实是新方法,但没有代码。
您所说的“抽象”可能是指父类中的方法不执行任何操作,无害,并且仍然被调用。这是不同的东西,不是抽象类,但仍然是一个有效的“模式”。
有时,在编写类层次结构时,我会声明一个没有代码的全新“抽象”方法,并且必须在子类中重新声明。
有时,我声明一个全新的方法,它有一个空的块代码,但是,不执行任何操作,并且仍然被调用。工作原理类似于“抽象”方法,但不是“抽象”方法。
在课堂上,我也使用“DoNothing”方法。
class Parent {
function doNothing() {
// does nothing, but don't remove me !!!
}
// im a new method, but, and Im abstract,
// I must be overriden in child classes
abstract function imVirtual();
// im a new method, but, Im NOT abstract,
// I don't need to be overriden, unless you want it
function imAlsoVirtual() {
deleteHardDriveWithoutAsking();
}
// im a new method, but, Im NOT abstract
function imVirtualAndHarmless() {
doNothing();
}
} // class Parent
class Child extends Parent {
// Im overriden from an abstract method
function imVirtual() {
$do = false;
}
// Im overriden from a non-abstract method
// Im also extending previous method
function imAlsoVirtual() {
if (askUserFirst()) {
parent::imAlsoVirtual();
}
}
// im a new method, but, Im NOT abstract
function imVirtualAndHarmless() {
parent::imVirtualAndHarmless();
sayHello();
}
// im a new method
function imNewShinnyMethod() {
sayGoodBye();
}
} // class Child
正如 @KingCrunch 提到的,
abstract
函数不包含主体,仅包含足迹。如果您有兴趣扩展功能,只需重新使用方法名称,然后使用 parent::
来调用基本函数的方法:
class Foo
{
function Test()
{
echo "Foo->Test();\r\n";
}
}
class Bar extends Foo
{
function Test()
{
parent::Test();
echo "Bar->Test();\r\n";
}
}
$foo = new Bar();
$foo->Test();
输出:
Foo->Test();
Bar->Test();