PHP Abstract Classes


In PHP, abstract classes are a fundamental concept of object-oriented programming (OOP) that provide a way to define a template for other classes. Unlike regular classes, abstract classes cannot be instantiated directly. Instead, they act as blueprints, providing structure for child classes by defining abstract methods, which the child classes are required to implement.

Abstract classes are particularly useful when multiple classes share some common behavior, but also need to provide their own specific implementations for certain methods. They allow developers to enforce consistency, improve code reuse, and create a scalable architecture.

What is an Abstract Class?

An abstract class is essentially a class that may include both concrete methods (fully defined) and abstract methods (declared but not defined). Abstract methods are placeholders that child classes must implement.

Key characteristics of abstract classes in PHP:

  • Cannot be instantiated directly – attempting to create an object of an abstract class will cause an error.

  • Can include properties, constants, and regular methods with complete functionality.

  • Can include one or more abstract methods.

  • Forces any non-abstract subclass to implement all abstract methods.

By using abstract classes, developers can define a common structure for related classes while leaving certain behaviors to be defined in the subclasses.

Declaring an Abstract Class

To define an abstract class in PHP, use the abstract keyword before the class definition. Abstract methods are also defined using the abstract keyword and must not have a body.

abstract class Vehicle {
    public $brand;

    // Abstract method – must be implemented by child classes
    abstract public function start();

    // Regular method with complete functionality
    public function setBrand($brand) {
        $this->brand = $brand;
    }
}

Here, Vehicle is an abstract class with a regular method setBrand() and an abstract method start(). Any class that extends Vehicle must implement the start() method.

Implementing Abstract Methods in Child Classes

Child classes that inherit from an abstract class must provide implementations for all abstract methods.

class Car extends Vehicle {
    public function start() {
        echo $this->brand . " car has started.<br>";
    }
}

$car = new Car();
$car->setBrand("Toyota");
$car->start(); // Outputs: Toyota car has started.

Here, the Car class implements the abstract method start(). Without this implementation, PHP would throw a fatal error.

Abstract Classes with Properties and Regular Methods

Abstract classes can include properties and regular methods, which allows you to define shared functionality that child classes can use directly:

abstract class Animal {
    public $name;

    public function setName($name) {
        $this->name = $name;
    }

    abstract public function makeSound();
}

class Dog extends Animal {
    public function makeSound() {
        echo $this->name . " says Woof!<br>";
    }
}

$dog = new Dog();
$dog->setName("Buddy");
$dog->makeSound(); // Outputs: Buddy says Woof!

In this example, setName() is a regular method available to all child classes, while makeSound() is abstract and requires a specific implementation for each animal type.

Abstract Class with Constructor

Abstract classes can also include constructors, allowing child classes to inherit and reuse initialization logic:

abstract class Shape {
    protected $color;

    public function __construct($color) {
        $this->color = $color;
    }

    abstract public function area();
}

class Rectangle extends Shape {
    private $length;
    private $width;

    public function __construct($color, $length, $width) {
        parent::__construct($color); // Call parent constructor
        $this->length = $length;
        $this->width = $width;
    }

    public function area() {
        return $this->length * $this->width;
    }

    public function display() {
        echo "Rectangle color: " . $this->color . ", Area: " . $this->area() . "<br>";
    }
}

$rect = new Rectangle("Red", 5, 10);
$rect->display(); // Outputs: Rectangle color: Red, Area: 50

Constructors in abstract classes help avoid repeating initialization logic in every child class.

Why Use Abstract Classes?

  1. Provide a blueprint for child classes – Ensures that subclasses implement required methods.

  2. Code reuse – Shared methods and properties are defined once in the abstract class.

  3. Maintain consistency – Enforces a consistent API or structure across related classes.

  4. Polymorphism – Allows treating objects of different child classes as instances of the abstract parent, enabling flexible design patterns.

Example of polymorphism:

abstract class Vehicle {
    abstract public function start();
}

class Car extends Vehicle {
    public function start() {
        echo "Car started.<br>";
    }
}

class Bike extends Vehicle {
    public function start() {
        echo "Bike started.<br>";
    }
}

$vehicles = [new Car(), new Bike()];
foreach ($vehicles as $vehicle) {
    $vehicle->start();
}

Output:

Car started.
Bike started.

This demonstrates how abstract classes allow different implementations to be treated uniformly.

Best Practices

  • Use abstract classes when multiple classes share common behavior but require specific implementations.

  • Keep the number of abstract methods reasonable; too many can make the design overly complex.

  • Use constructors in abstract classes for shared initialization.

  • Combine abstract classes with interfaces for better flexibility when enforcing method contracts.

  • Avoid instantiating abstract classes directly.

Common Mistakes

  • Trying to create an instance of an abstract class.

  • Forgetting to implement all abstract methods in non-abstract child classes.

  • Adding a body to abstract methods, which is not allowed.

  • Using abstract classes when a simple interface would suffice for defining contracts.

Summary of the Tutorial

  • Abstract classes serve as blueprints for child classes.

  • They can contain abstract methods, regular methods, and properties.

  • Child classes must implement all abstract methods or be declared abstract themselves.

  • Constructors and regular methods in abstract classes allow shared functionality.

  • Abstract classes promote code reuse, consistency, and maintainability, forming the foundation of robust PHP OOP designs.

Mastering abstract classes is essential for writing clean, organized, and scalable PHP applications, especially when multiple classes share common traits but require their own specific behaviors.


Practice Questions

  1. Create an abstract class Vehicle with an abstract method startEngine(). Create child classes Car and Bike that implement startEngine() differently. Instantiate both and call the method.

  2. Write an abstract class Animal with a property $name and an abstract method makeSound(). Create subclasses Dog and Cat that implement makeSound() to print their respective sounds.

  3. Create an abstract class Shape with an abstract method area(). Create subclasses Rectangle and Circle that implement area(). Calculate and display areas for each.

  4. Write an abstract class Employee with properties $name and $salary and an abstract method calculateBonus(). Create subclasses Manager and Developer that implement calculateBonus() differently.

  5. Create an abstract class BankAccount with a constructor to initialize accountNumber and an abstract method getAccountInfo(). Implement two child classes SavingsAccount and CheckingAccount. Display account details for each.

  6. Write an abstract class Transport with a regular method fuelType() returning "Diesel". Add an abstract method move(). Create a subclass Truck that implements move() and uses fuelType() from the parent.

  7. Create an abstract class Employee with an abstract method work(). Create a subclass Intern that implements work(). Instantiate an Intern object and call the method.

  8. Write a multi-level abstract class example: Appliance (abstract) → KitchenAppliance (abstract) → Blender (concrete). Implement all abstract methods in Blender and demonstrate usage.

  9. Create an abstract class Payment with an abstract method processPayment($amount). Create subclasses CreditCardPayment and PayPalPayment with different implementations. Demonstrate polymorphism by storing both in an array and calling processPayment().

  10. Write an abstract class Logger with a constructor that sets a $logFile property and an abstract method log($message). Create a subclass FileLogger that implements log() to append messages to the file.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top