Home » PHP Abstract Classes Tutorial with Examples

PHP Abstract Classes Tutorial with Examples

In PHP, an abstract class is a class that cannot be instantiated directly and is designed to be extended by other classes. Abstract classes allow you to define methods and properties that child classes must implement or extend, making them an essential tool for building flexible and scalable applications in object-oriented programming (OOP).

In this tutorial, we will cover:

Let’s explore each topic with examples and explanations.

1. What is an Abstract Class?

An abstract class is a class that cannot be instantiated on its own. It serves as a blueprint for other classes to extend. An abstract class can contain abstract methods (which have no implementation) and concrete methods (which have full implementations).

Key points about abstract classes:

  • They cannot be instantiated directly.
  • They can contain both abstract and non-abstract (concrete) methods.
  • Child classes must implement all abstract methods of the parent abstract class.
  • Abstract classes are declared using the abstract keyword.

2. Defining an Abstract Class

To define an abstract class in PHP, use the abstract keyword before the class definition. The abstract class can include both abstract and non-abstract methods.

Example (Defining an Abstract Class):

<?php
// Define an abstract class
abstract class Animal {
    public $name;

    // Constructor to initialize the name
    public function __construct($name) {
        $this->name = $name;
    }

    // Abstract method (no implementation)
    abstract public function makeSound();

    // Concrete method (with implementation)
    public function describe() {
        echo "This is a " . $this->name . "\n";
    }
}
?>
  • In this example, the Animal class is an abstract class. It has one abstract method (makeSound()) that must be implemented by any subclass, and one concrete method (describe()), which provides an implementation.

3. Abstract Methods

An abstract method is a method declared in an abstract class but without an implementation. Child classes that extend the abstract class must provide the implementation for all abstract methods.

Syntax for Abstract Method:

abstract public function methodName();

Example (Abstract Methods):

<?php
abstract class Animal {
    abstract public function makeSound();  // Abstract method
}
  • Abstract methods do not contain a body. Child classes are responsible for implementing these methods.

4. Extending an Abstract Class

A child class must extend an abstract class and implement all its abstract methods. If the child class fails to implement all abstract methods, it must also be declared abstract.

Example (Extending an Abstract Class):

<?php
// Abstract class Animal
abstract class Animal {
    public $name;

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

    // Abstract method
    abstract public function makeSound();

    // Concrete method
    public function describe() {
        echo "This is a " . $this->name . "\n";
    }
}

// Child class Dog that extends Animal
class Dog extends Animal {
    // Implement the abstract method
    public function makeSound() {
        echo "Bark\n";
    }
}

// Child class Cat that extends Animal
class Cat extends Animal {
    // Implement the abstract method
    public function makeSound() {
        echo "Meow\n";
    }
}

// Instantiate the objects and call methods
$dog = new Dog("Dog");
$dog->describe();  // Outputs: This is a Dog
$dog->makeSound();  // Outputs: Bark

$cat = new Cat("Cat");
$cat->describe();  // Outputs: This is a Cat
$cat->makeSound();  // Outputs: Meow
?>
  • In this example, both the Dog and Cat classes extend the Animal abstract class and implement the makeSound() method. The describe() method is inherited and used directly from the abstract class.

5. Using Abstract Classes with Concrete Methods

Abstract classes can contain both abstract methods (which must be implemented by child classes) and concrete methods (which already have an implementation). This allows you to share common functionality among child classes while ensuring that specific behavior is implemented in the child classes.

Example (Abstract Class with Concrete Methods):

<?php
abstract class Vehicle {
    public $make;
    public $model;

    public function __construct($make, $model) {
        $this->make = $make;
        $this->model = $model;
    }

    // Concrete method
    public function displayInfo() {
        echo "Make: " . $this->make . "\n";
        echo "Model: " . $this->model . "\n";
    }

    // Abstract method
    abstract public function startEngine();
}

class Car extends Vehicle {
    // Implement the abstract method
    public function startEngine() {
        echo "Car engine started\n";
    }
}

class Motorcycle extends Vehicle {
    // Implement the abstract method
    public function startEngine() {
        echo "Motorcycle engine started\n";
    }
}

// Instantiate objects and use methods
$car = new Car("Toyota", "Corolla");
$car->displayInfo();  // Outputs: Make: Toyota, Model: Corolla
$car->startEngine();  // Outputs: Car engine started

$bike = new Motorcycle("Honda", "CBR600");
$bike->displayInfo();  // Outputs: Make: Honda, Model: CBR600
$bike->startEngine();  // Outputs: Motorcycle engine started
?>
  • In this example, the abstract class Vehicle contains both a concrete method (displayInfo()) and an abstract method (startEngine()). The child classes Car and Motorcycle implement the startEngine() method but reuse the displayInfo() method from the abstract class.

6. Difference Between Abstract Classes and Interfaces

While both abstract classes and interfaces provide ways to define methods that must be implemented by child classes, there are key differences between them:

Aspect Abstract Classes Interfaces
Method Implementation Can contain both abstract and concrete methods Can only declare method signatures, no implementation
Properties Can have properties Cannot have properties
Multiple Inheritance A class can extend only one abstract class A class can implement multiple interfaces
Constructor Can have a constructor Cannot have constructors

Example of Abstract Class vs. Interface:

<?php
// Abstract class
abstract class Animal {
    abstract public function makeSound();
    public function sleep() {
        echo "Sleeping...\n";
    }
}

// Interface
interface Flyable {
    public function fly();
}

// Class implementing both abstract class and interface
class Bird extends Animal implements Flyable {
    public function makeSound() {
        echo "Chirp chirp\n";
    }

    public function fly() {
        echo "The bird is flying\n";
    }
}

$bird = new Bird();
$bird->makeSound();  // Outputs: Chirp chirp
$bird->fly();        // Outputs: The bird is flying
$bird->sleep();      // Outputs: Sleeping...
?>
  • In this example, Bird extends the abstract class Animal and implements the Flyable interface. This shows how you can combine both abstract classes and interfaces.

7. Example Use Case: Shape and Circle Classes

Let’s explore a more practical use case where we define a Shape abstract class and extend it with specific shape classes like Circle.

Example (Shape and Circle):

<?php
// Abstract class Shape
abstract class Shape {
    protected $color;

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

    // Abstract method to calculate area
    abstract public function calculateArea();

    // Concrete method to get the color
    public function getColor() {
        return $this->color;
    }
}

// Child class Circle that extends Shape
class Circle extends Shape {
    private $radius;

    public function __construct($radius, $color = "red") {
        parent::__construct($color);  // Call the parent constructor
        $this->radius = $radius;
    }

    // Implement the abstract method
    public function calculateArea() {
        return pi() * pow($this->radius, 2);
    }
}

// Instantiate a Circle object
$circle = new Circle(5, "blue");

echo "Circle color: " . $circle->getColor() . "\n";  // Outputs: Circle color: blue
echo "Circle area: " . $circle->calculateArea() . "\n";  // Outputs: Circle area: 78.539816339745
?>
  • In this example, the abstract class Shape defines a method calculateArea(), which is implemented by the Circle class. The getColor() method is inherited from the abstract class and used directly.

Summary of PHP Abstract Classes:

Concept Description
abstract class Defines a class that cannot be instantiated directly.
abstract method A method declared without implementation, to be implemented by child classes.
Concrete Methods Abstract classes can contain concrete methods that are inherited by child classes.
extends Keyword used to extend an abstract class.
parent::__construct() Used to call the parent class constructor from a child class.
Difference from Interface Abstract classes can have both abstract and concrete methods, whereas interfaces can only declare method signatures.

 

Conclusion

Abstract classes in PHP are a powerful tool for building extensible and maintainable object-oriented applications. They allow you to define a common structure for related classes, while also ensuring that certain methods are implemented in child classes. In this tutorial, we covered:

  • Defining abstract classes and abstract methods.
  • Extending abstract classes and implementing abstract methods.
  • Using concrete methods in abstract classes.
  • The key differences between abstract classes and interfaces.
  • A practical use case with Shape and Circle classes.

 

You may also like