What are Abstract Classes in PHP? Simple examples

An abstract class in PHP is a special type of class that cannot be instantiated directly.

That means that you cannot create an object from an abstract class.

To define an abstract class you need to use the abstract keyword. We use this keyword to both the class and its methods.

Code example showing how we get an error when trying to instantiate an object from an abstract class.
Trying to instantiate an object from an abstract class gets us a warning.

Regarding methods, an abstract class is not mandatory to contain abstract methods.

But it can include one or more of these methods.

These abstract methods are declared but not implemented in the abstract class.

An abstract class can also include regular methods (methods with implementation). We call them concrete methods.

Code example with an abstract class containing both a concrete and an abstract method.
An abstract class can include regular (concrete) methods. Notice how the abstract method is declared but not implemented.

If a class contains an abstract method, then it is mandatory for that class to be abstract.

Code example showing how an abstract method declaration should be held inside an abstract class.
The abstract keyword is missing here so we get a Fatal error message.

The extended class must implement the abstract method if there is one.

Code example of how we get a warning when extending an abstract class without declaring the abstract method.
If a parent class has declared abstract methods these methods must be also declared (and implemented) in the extended classes.

Polymorphism Using Abstract Classes

An abstract class works as a template for other classes.

Let’s create another class MyCat that extends the Pet class

Extending a second class named MyCat.

Now to calculate how much kibble to give my cat I use the same abstract method howMuch(). Only this time I do it a little differently since cats are different and the definite factor is not only the size but also the level of activity.

So I introduce the $indoor variable. An indoor cat is, usually, less active so I factor this into the method.

Using the extended classes to instantiate two new object and then printing the same howMuch() method.

This is an example of polymorphism. The two abstract methods do the same thing but they do it differently.

Concluding

Abstract classes let as create a blueprint for other classes, ensuring that all extended classes implement specific methods. Thank to them we can enforce a consistent structure and allow for code reuse among related classes.

Although my blog doesn’t support comments, feel free to reply via email or X.