Inheritance allows a class to reuse, extend, and specialise the behaviour of another class. The child class (subclass) inherits all public and protected members of the parent class (superclass).
Use extends to inherit from a parent class.
Override a parent method by redefining it in the child.
Call the parent's implementation with parent::methodName().
PHP supports single inheritance only — a class can have only one parent.
Example
<?php
class Animal
{
public function __construct(
protected string $name,
protected int $age
) {}
public function speak(): string
{
return "{$this->name} makes a sound.";
}
public function describe(): string
{
return "{$this->name} is {$this->age} years old.";
}
}
class Dog extends Animal
{
public function __construct(
string $name,
int $age,
private string $breed
) {
parent::__construct($name, $age); // call parent constructor
}
// Override speak()
public function speak(): string
{
return "{$this->name} barks: Woof!";
}
// Extend describe()
public function describe(): string
{
return parent::describe() . " Breed: {$this->breed}.";
}
}
class Cat extends Animal
{
public function speak(): string
{
return "{$this->name} meows: Meow!";
}
}
$dog = new Dog('Rex', 3, 'Labrador');
$cat = new Cat('Luna', 2);
echo $dog->speak(); // Rex barks: Woof!
echo $dog->describe(); // Rex is 3 years old. Breed: Labrador.
echo $cat->speak(); // Luna meows: Meow!
// instanceof checks
echo ($dog instanceof Animal) ? 'yes' : 'no'; // yes
echo ($dog instanceof Dog) ? 'yes' : 'no'; // yes
echo ($dog instanceof Cat) ? 'yes' : 'no'; // no
Pro Tip
Tip: Favour composition over inheritance for code reuse. Deep inheritance hierarchies become brittle and hard to reason about. Use inheritance when there is a true "is-a" relationship; inject collaborator objects for "has-a" or "uses-a" relationships.