Skip to main content

PHP - Abstract Classes and Methods

Some methods only make sense once a child class fills in the details. An abstract method is exactly that: the parent declares it but gives it no implementation, leaving that work to the child class or classes.

A class with at least one abstract method is called an abstract class. Its purpose is enforcement: every derived class (child class) has to implement the abstract methods declared by the parent.

Both abstract classes and abstract methods are marked with the abstract keyword.

Here is how that looks in practice:

Example

Car is abstract and declares an abstract intro() method, which its two child classes each implement:

Prompt
Create an abstract Car class with a public $name property, a constructor, and an abstract intro() method. Then create Audi and Citroen child classes that each implement intro() returning a different string. Create objects and echo their intros.
Output: PHP script

Example Explained

Audi and Citroen both extend the abstract Car class. Because of that inheritance, they can use its public $name property and its public __construct() method.

intro() is different. It is abstract, so each child class has to provide its own implementation.


Notes on Abstract Classes

A child class has to follow some rules when it implements an abstract method. The method must keep the same name, and its access modifier must be the same or less restrictive. For example, an abstract method declared protected can stay protected or become public in the child, but it can never become private. The type and number of required arguments must also match, although the child is free to add optional arguments.

To sum up, these rules apply when a child class inherits from an abstract class:

  • The method in the child class has the same name as the abstract method and redeclares it
  • Its access modifier is the same as the parent's or less restrictive
  • It takes the same number of required arguments, and it may add optional ones

PHP - Abstract Method with Argument

Abstract methods can take arguments too. The next two examples show how that works:

Example

The abstract method declares one argument, $name, and the child class implements it with that same argument:

Prompt
Create an abstract ParentClass with an abstract protected method prefixName($name). Create a ChildClass that implements prefixName and adds Mr. or Mrs. prefix based on the name. Test with John Doe, Jane Doe, and Baby Doe.
Output: PHP script

Example

Here, the child class adds two optional arguments that the parent's abstract method does not declare:

Prompt
Create an abstract ParentClass with an abstract protected method prefixName($name). Create a ChildClass that implements prefixName with two optional extra parameters $separator and $greet. Test with John Doe and Jane Doe.
Output: PHP script