Inheritance allows a class (child) to extend another class (parent), reusing its properties and methods while adding or overriding behaviour.
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!
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
final class Singleton {} // cannot be extended
class Base {
final public function lock(): void {} // cannot be overridden
}