PHP class inheritance: A practical guide

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

Class inheritance allows for the extension and reuse of existing code without redundancy. This fundamental component of object-oriented programming in PHP simplifies complex tasks by establishing hierarchical relationships between classes.

Introduction to Class Inheritance

In PHP, class inheritance plays a critical role in organizing and reusing code. It involves creating a new class (the child) by extending an existing class (the parent), enabling the child to inherit methods and properties from the parent. Understanding this concept is vital for PHP developers to create flexible and maintainable code.

<?php
    class Vehicle {
        public $wheels = 4;
        public function startEngine() {
            return "Engine started";
        }
    }

    class Car extends Vehicle {
        public function openTrunk() {
            return "Trunk opened";
        }
    }

    $car = new Car();
    echo $car->startEngine();
    // Output: Engine started
    echo $car->openTrunk();
    // Output: Trunk opened
?>

Using Protected Members

Protected members are accessible within the class itself and by inheriting and parent classes. This visibility is essential when you want to hide some of the class details but still allow the child classes to access them.

<?php
    class ElectricVehicle extends Vehicle {
        protected $batteryLevel = 100;

        protected function useBattery() {
            $this->batteryLevel--;
        }
    }

    class ElectricCar extends ElectricVehicle {
        public function drive() {
            $this->useBattery();
            echo "Driving with battery at {$this->batteryLevel}%";
        }
    }

    $electricCar = new ElectricCar();
    $electricCar->drive();
    // Output: Driving with battery at 99%
?>

Overriding Methods

Overriding allows child classes to provide specific implementations of functions defined in their parent classes. This is crucial when you want a child class to have a modified behavior of a method defined in its parent class.

<?php
    class SportsCar extends Car {
        public function startEngine() {
            return "Sports engine started with a roar!";
        }
    }

    $sportsCar = new SportsCar();
    echo $sportsCar->startEngine();
    // Output: Sports engine started with a roar!
?>

Abstract Classes and Methods

Abstract classes are used to create a base class that cannot be instantiated on its own but can define methods and properties that must be implemented by any extending subclasses. This enforces a contract for the child classes to implement certain behaviors.

<?php
    abstract class Shape {
        abstract protected function getArea();
    }

    class Circle extends Shape {
        protected $radius;

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

        protected function getArea() {
            return pi() * ($this->radius ** 2);
        }
    }

    $circle = new Circle(4);
    echo $circle->getArea();
    // Output: 50.265482457
?>

Final Classes and Methods

Through the use of the final keyword, PHP allows developers to prevent classes and methods from being extended or overridden. This ensures that critical functionalities remain unaltered throughout the inheritance chain.

<?php
    class BaseClass {
        final public function moreLogic() {
            return "This method cannot be extended or overridden.";
        }
    }

    class ExtendedClass extends BaseClass {
        // ERROR: Cannot override final method BaseClass::moreLogic()
    }
?>

Composition over Inheritance

Sometimes using composition (including one class within another) is more suitable than inheritance. This approach provides greater flexibility in code design and avoids the issues that can arise with deep inheritance hierarchies.

<?php
    class Engine {
        public function start() {
            return "Engine on";
        }
    }

    class CarWithEngine {
        private $engine;

        public function __construct() {
            $this->engine = new Engine();
        }

        public function startCar() {
            return $this->engine->start();
        }
    }

    $myCar = new CarWithEngine();
    echo $myCar->startCar();
    // Output: Engine on
?>

Conclusion

In this guide, we delved into PHP class inheritance with practical examples increasing in complexity. Through inheritance, PHP developers can create more efficient and manageable code, inheriting and extending functionality as needed.