16

我原以为很多人会想知道这是否可能,但我找不到任何重复的问题......请纠正我。

我只想知道PHP是否提供纯虚函数。我想要以下

class Parent {
   // no implementation given
   public function foo() {
      // nothing 
   }
}

class Child extends Parent {
   public function foo() {
      // implementation of foo goes here
   }
}

非常感谢。

4

4 回答 4

20

您可以创建抽象函数,但您也需要将父类声明为抽象:

abstract class Parent {
   // no implementation given
   abstract public function foo();
}

class Child extends Parent {
   public function foo() {
      // implementation of foo goes here
   }
}
于 2011-09-29T17:03:09.490 回答
4

在 Parent 类中将方法声明为抽象:

abstract public function foo();
于 2011-09-29T17:02:34.723 回答
3

抽象类

abstract class Parent {
   // no implementation given
   abstract public function foo();
   }
}

class Child extends Parent {
   public function foo() {
      // implementation of foo goes here
   }
}
于 2011-09-29T17:04:09.973 回答
1

是的,这种类型的解决方案是可能的,它被称为多态,你可以在不声明抽象类或接口的情况下做到这一点。

于 2011-09-29T17:01:52.167 回答