PHP Inheritance

PHP Inheritance

Inheritance allows a class (child) to extend another class (parent), reusing its properties and methods while adding or overriding behaviour.

1 - Basic Inheritance

class Animal {
    public function __construct(protected string $name) {}

    public function speak(): string {
        return "$this->name makes a sound.";
    }
}

class Dog extends Animal {
    public function speak(): string {
        return "$this->name barks!";
    }

    public function fetch(): string {
        return "$this->name fetches the ball!";
    }
}

$dog = new Dog("Rex");
echo $dog->speak();  // Rex barks!
echo $dog->fetch();  // Rex fetches the ball!

2 - parent:: — Calling the Parent

class Vehicle {
    public function __construct(protected string $brand) {}

    public function info(): string {
        return "Brand: {$this->brand}";
    }
}

class ElectricCar extends Vehicle {
    public function __construct(string $brand, private int $range) {
        parent::__construct($brand);
    }

    public function info(): string {
        return parent::info() . " | Range: {$this->range} km";
    }
}

$car = new ElectricCar("Tesla", 500);
echo $car->info(); // Brand: Tesla | Range: 500 km

3 - Preventing Overrides

final class Singleton {}  // cannot be extended

class Base {
    final public function lock(): void {}  // cannot be overridden
}

Note: PHP only supports single inheritance — a class can extend only one parent. Use interfaces and traits to compose behaviour from multiple sources.

-Tip-