Are there pure virtual functions in PHP like with C++
Asked Answered
H

4

16

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.

Hideaway answered 29/9, 2011 at 17:0 Comment(0)
A
21

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
   }
}
Ariadne answered 29/9, 2011 at 17:3 Comment(4)
A pure virtual function requires that is defined in a sub-class. If not an error should occur. Will an error occur if foo() is not defined. This is key.Dispersoid
Yes, if you extend Parent but do not define foo you will get an error (unless your subclass is also abstract, in which case it cannot be instantiated and any non-abstract subclasses must define foo themselves). For more information, see the PHP manual, which states that "all methods marked abstract in the parent's class declaration must be defined by the child".Ariadne
And when a class is declared abstract does it mean all it's functions must be abstract (that is, pure virtual), or you may create virtual and final functions (I mean functions not prepended with the abstract keyword)?Intervene
@Intervene An abstract class may have abstract or concrete functions. See the docs for more details.Ariadne
V
4

Declare the method as abstract in the Parent class:

abstract public function foo();
Viscounty answered 29/9, 2011 at 17:2 Comment(0)
S
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
   }
}
Sterling answered 29/9, 2011 at 17:4 Comment(0)
K
1

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

Kettledrum answered 29/9, 2011 at 17:1 Comment(2)
Creating an empty method without declaring the method as abstract (like in the question) does not reflect C++ pure-virtual method behaviour (which is the same as abstract methods in PHP).Ariadne
This is the best answer in the world for anything ever. I hope that one day when my kids grow up I can show them this answer and they can be impressed as much as I am right now. Generations of programmers are better because of it, you probably single handedly saved millions of lives here - well done sir, well done. Have a +1.Teutonic

© 2022 - 2024 — McMap. All rights reserved.