Using Abstract Classes Correctly with PHP Code Examples in 2023

What is an Abstract Class in PHP

An abstract class in PHP is a class with at least one not implemented method. You cannot use an abstract class directly but must extend it with a child class. The child classes are supposed to provide an implementation for these abstract methods.

Using an Abstract Class in PHP

Create an abstract class in PHP by adding the modifier “abstract” before noting the access level. Do the same thing for any methods you want to require child classes to implement. You can see the below for an example.

Abstract Class Code Example

<?php

abstract public class Bird
{
    abstract public function fly()
    {}

    public function walk()
    {
       // do something concrete here
}


public class Flamingo extends Bird
{
    public function fly()
    {
      // do something here
    }
}

But why and what is the purpose of all this?

That’s precisely why we are writing an article on this very topic. So, jump in and stay with us to learn more about abstract classes in PHP.

What does ‘Abstract’ mean?

“Abstract-ion” generally means a “layer of simplicity” or a “layer of convenience” over a complicated system.

Providing or creating such a layer is abstracting or hiding the complexities.

But how? Let’s cut these terminologies and definitions and understand them with examples.

A real-world example

Have you ever seen the internals of a TV remote? Probably not unless you are a hardware engineer who designs those. It won’t be convenient for a regular user to interact with complex circuits and hardware. 

Abstraction
Abstraction

So, we have these intuitive remote covers with nice buttons and labels so that the most naive user can easily understand the functions without worrying about internal functioning.

In application development

Abstraction is a core idea in software development, and we use abstractions quite often, knowingly or unknowingly. Note that we don’t mean “Abstract classes” yet but more generally about abstraction as a “layer of simplicity.”

For example, we live in times when UI/UX is a serious business in app development. Apps without intuitive UI/UX are meaningless. But why UI? Think of UI as an abstraction over the underlying implementation of an application.

Mobile App UI

Back in the old days, software was console-based, even operating systems, and if we bring them back into the present world, it won’t be less than a catastrophe for most of us.

Abstract Class in PHP

In backend development

Backend development has a wider scope than front-end development. It is what you don’t see on your monitor, yet it is the reason for all the functions that software can perform. That’s why backend developers end up learning a lot of technologies to build backend systems.

backend-frontend

So, where does abstraction fit in backend systems? Pretty much everywhere. Even backend developer relies on abstractions to use other systems, libraries, and APIs because they don’t reinvent the wheel but try to reuse existing functionalities as much as possible, and that’s why integrations are a lifeline in backend development.

For instance, if an application uses AWS, then it has to use AWS SDK to use AWS services programmatically. Think of SDKs as abstractions because the internals is not necessarily important as long as SDK methods perform the intended functions. It doesn’t matter how the method internally uses EC2 or S3 because they are abstracted away by SDK.

And the list goes on. APIs & wrapper functions, SDKs, and libraries are all based on the same idea. 

We assume the idea is clear to some degree, at least. So, let’s move to using an abstract class in PHP.

Abstract Class in PHP

An abstract class in Object Oriented PHP is a class with at least one abstract method. An abstract method has a definition but no implementation. 

<?php


abstract class AbstractClass 
{


    abstract public function AbstractFunction();
}

?>

No implementation, doesn’t make sense?

An abstract class rests at the top of a hierarchy and lets its child classes implement the abstract functions.

<?php


abstract class AbstractClass {


    abstract public function AbstractFunction();
}


class ChildClass extends AbstractClass {


    public function AbstractFunction() {
        echo "Hello";
    }
}


?>

Well, if you are not familiar with polymorphism OOP then any of these won’t make sense to you. 

So, what is polymorphism? 

What is Polymorphism

Polymorphism (Poly means many & morphs means forms)  is a fundamental OOP concept in which:

  • An object can exist in many forms.
  • A super entity can represent more specialized entities. 
  • Specialized entities can substitute if they are related to the same super-entity.

In OOP terms, the super-entity could be a class or an interface, and specialized entities are classes that extend or implements them. More precisely, we are talking about inheritance in OOP.

Why Polymorphism?

The why of polymorphism qualifies as a separate article, but it is a key ingredient of flexible and scalable software systems. If you want a more practical outlook, consider reading design pattern articles.

Consider an Animal abstract class with specialized/child classes (Cat & Dog) extending it.

Abstract Class in PHP
<?php


abstract class Animal {


    abstract public function make sound();
}


class Cat extends Animal {


    public function makeSound() {
        echo "Meow";
    }
}


class Dog extends Animal {


    public function makeSound() {
        echo "Woof";
    }
}


function App() {


    $animal = new Cat();


    //Cat is an Animal
    $animal instanceof Animal; //true


    $animal->makeSound(); //Meow


    $animal = new Dog();


    //Dog is also an Animal
    $animal instanceof Animal; //true


    $animal->makeSound(); //Woof
}

?>

The instanceof verifies that both Cat and Dog are Animal instances. Although we use new Cat() and new Dog(), yet they are instances of Animal (Polymorphism).

A software module can use polymorphically refer to specialized/concrete classes via their superclasses or interfaces hence using abstraction than concrete instances.

Yes, we know that it is a challenging idea, so we recommend going through design patterns to see this idea in use.

Abstract Class Syntax in PHP

Well, you have seen code snippets already but let’s go through the syntax once before we see some caveats.
Declare a class in PHP using the keyword abstract before the class keyword followed by the class name.

abstract class AbstractClass {
   
}


An abstract class has at least one abstract method. Declaring an abstract method is similar; just use the keyword abstract before the access modifier (optional, public by default) and the function keyword.

abstract public function AbstractFunction();

Abstract methods don’t have an implementation, so we don’t need to open a block with parenthesis {} but rather just a statement ending with a colon :

That’s the syntax. Besides, an abstract class can include instance variables, non-abstract methods, and static or non-static members. Pretty much everything a normal class would have.

Caveats | Abstract Class in PHP

– Use the same abstract method name in the child class that implements that abstract method.

<?php


abstract class AbstractClass {


    abstract public function AbstractFunction();
}


class ChildClass extends AbstractClass {


    public function AbstractFunction() {
        echo "I'm no longer abstract";
    }
}
?>

– Use the same or less restricted access modifier as the abstract method. For example, if the abstract method uses the protected access modifier, then the child class can use public or protected, not private.

<?php


abstract class AbstractClass {


    abstract protected function AbstractFunction();
}


class ChildClass extends AbstractClass {


    //Dont do this
    private function AbstractFunction() {
        echo "Protected should not be private";
    }
}


class AnotherChildClass extends AbstractClass {
   
    //This is right
    public function AbstractFunction() {
        echo "Public is less strict than private";
    }
}


class YetAnotherChildClass extends AbstractClass {
   
    //This is also right
    protected function AbstractFunction() {
        echo "Protected as the abstract function";
    }
}
?>

– The number of required arguments should not change. However, child classes can introduce optional arguments.

<?php


abstract class AbstractClass {


    abstract protected function AbstractFunction($arg1, $arg2);
}


class ChildClass extends AbstractClass {


    //Wrong because $arg2 is missing
    private function AbstractFunction($arg1) {
        echo "Yikes! There were two required arguments";
    }
}


class AnotherChildClass extends AbstractClass {
   
    //This is right
    public function AbstractFunction($arg1, $arg2) {
        echo "Cool! Both required arguments are there";
    }
}


class YetAnotherChildClass extends AbstractClass {
   
    //This is also right
    protected function AbstractFunction($arg1, $arg2, $optional="Optional argument") {
        echo "No problem with optional arguments";
    }
}
?>

Super! Guess what? That’s all we need to know about an abstract class in PHP.

Abstract Class vs. Interface

If you are coming from Interfaces in PHP, then you should definitely be curious about “abstract class vs interface.” The fact is that they are meant for the same end: Abstraction & Polymorphism.

Yet they have their differences, and they exist because sometimes we need abstract classes and other times interfaces in PHP. Let’s see some important differences between these two.

Abstract ClassInterface
They can have static, non-static, final, or non-final instance variables. They don’t have instance variables.
They can have both abstract and non-abstract methods.They can only have abstract methods.
Uses the abstract keyword followed by the class keyword and class name for declaration.Uses the interface keyword followed by a name.
Members can be public, protected, or private.Members are public by default.
An abstract class can implement interfaces and extend classes.An interface can extend to other interfaces only.

Benefits of an Abstract Class

Flexibility & Extensibility

More flexible and scalable systems exist because of abstraction and polymorphism. These two fundamental yet powerful concepts change how we design software. Programming languages provide interfaces and abstract classes to implement these concepts in programming.

Software modules should not be overly coupled. Some form of coupling has to exist, but it is always better to reduce the degree of dependency. This form of design is possible with generalized and generic structures and modules, and at the heart of generalization are polymorphism and abstraction.

In the animal class example, we have already seen that both the child classes Cat & Dog are of the type Animal. Now, if we have to extend this hierarchy and add more animals, we won’t have to worry much about how other modules use the specialized instances because they are all referred to as Animal types.

So, it becomes more of a plug-and-play design because you can plug in any specialized instance as long as it extends the Animal abstract class. Hence, we can extend the system easily.

Code Sharing

Unlike interfaces, abstract classes can have concrete methods, which means we can have common methods inside the abstract class. Any child class extending from that abstract class will inherit the same method and share the same implementation.

For example, suppose we define a method move() in the Animal abstract class and provide some implementation. In that case, the Cat & Dog will share the same moving functionality. 

Usability & Cohesion

Abstract classes provide one or more abstract methods. The child classes implement these methods, but implementation is hidden by the abstract method already. It doesn’t matter how a Cat class would implement makeSound() because it extends from the Animal class. We can call the makeSound() method on it without worrying about the implementation details.

While you may not notice it here in this super simple example, a layer of abstraction plays a vital role in simplifying complex systems that would otherwise be difficult to understand and use. 

Another factor is cohesion related to the idea of low coupling and flexible systems. Cohesiveness is when your class is one unit having similar responsibilities and fewer dependencies; then, it has fewer reasons to change. They are least affected when some other aspects of the code change.

Confining a change or limiting the scope of the change in a software system yields benefits in the long run when you have change requests or want to add features to your software system. 

Frequently Asked Questions

When to use an Abstract Class in PHP?

Use abstract methods when you want to:

  • Polymorphically use specialized/child classes.
  • Have less coupling between modules and more flexibility.
  • Want to share common methods but also declare non-concrete methods.

Why should we use Abstract Class in PHP?

You should use the abstract classes because they:

  • Enable you to use specialized classes polymorphically.
  • Abstract implementational details.
  • Make software modules less dependent on concrete instances and implementations.
  • Helps add flexibility, extensibility, and scalability to the software system.

How to use Abstract Class in PHP?

Following is the syntax of the abstract class in PHP.

<?php

abstract class AbstractClass {

    abstract protected function AbstractFunction();
    abstract public function AnotherAbstractFunction($arg1);
}

class ChildClass extends AbstractClass {

    protected function AbstractFunction() {
        echo "I'm no longer abstract";
    }

    public function AnotherAbstractFunction($arg1) {
        echo "I'm no longer abstract";
    }
    
}


?>

Using an Abstract Class in PHP like a Pro

The article is a deep dive into using an abstract class in PHP. Let’s review what we have seen thus far. Abstraction generally means a “layer of simplicity” that exists on top of a more complex layer dealing with the internals of a system. As users, we are often not interested in the internals but rather in the functions of a system.

That’s the reason why that “layer of simplicity” is important. Software systems are no different; they use abstractions to provide a simple point of interaction to promote usability. User interfaces, SDKs, APIs, and libraries all are based on similar ideas.

An abstract class in PHP is a construct that defines a class with at least one abstract (non-concrete) method that the child classes are supposed to override and provide an implementation.  

The syntax of an abstract class in PHP is quite simple. Declare a class and add the keyword abstract before the class keyword. Similarly, define abstract methods using the abstract keyword followed by access modifier (optional), function keyword, and name.

Abstract classes can have everything a normal class would have except abstract methods. So, we can define some concrete methods and thus share them in child classes via inheritance. Abstract classes can be used polymorphically, and hence we can have flexible and scalable systems.

So, that’s all for now. Hope you have enjoyed the article. Stay tuned at FuelingPHP.

PHP Object-Oriented Programming Learning Path

This article is part of our series on learning Object-oriented programming with PHP. It introduces some concepts, best practices and strategies to help you level up your skills. This is a great intro to growing into a successful programmer.


Article Categories

Article Tags