Are there pure virtual functions in PHP like with C++

牧云@^-^@ 提交于 2020-02-20 06:58:45

问题


I would have thought lots of people would have wondered whether this is possible but I can't find any duplicate questions... do correct me.

I just want to know whether PHP offers pure virtual functions. I want the following

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

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

Thanks very much.


回答1:


You can create abstract functions, but you need to declare the parent class as abstract, too:

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

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



回答2:


Declare the method as abstract in the Parent class:

abstract public function foo();



回答3:


There are abstract classes!

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

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



回答4:


Yes, that type of solution is possible, it's called polymorphism, you can do it without declaring an abstract class or an interface.



来源:https://stackoverflow.com/questions/7600771/are-there-pure-virtual-functions-in-php-like-with-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!