Inheritance lets one class build on another. The new class (the child) gets everything from the existing class (the parent) and can add more.
<?php
class Animal
{
public function __construct(protected string $name) {}
public function eat(): string
{
return $this->name . " is eating.";
}
}
class Dog extends Animal
{
public function bark(): string
{
return $this->name . " says woof!";
}
}
$dog = new Dog("Bruno");
echo $dog->eat() . "\n";
echo $dog->bark();
Bruno is eating.
Bruno says woof!
Dog did not write eat() or the constructor. It inherited them from Animal, and it added bark().
What is inherited
- All public and protected properties and methods.
- The constructor (if the child does not write its own).
Private members belong to the parent only. The child cannot use them.
The “is a” test
Inheritance fits when the child is a kind of the parent: a Dog is an Animal. If you would say “has a” (a Car has an Engine), use composition instead. See Composition vs Inheritance.
A child can add its own constructor
Call the parent constructor with parent::__construct().
<?php
class Vehicle
{
public function __construct(protected string $brand) {}
}
class Car extends Vehicle
{
public function __construct(string $brand, private int $doors)
{
parent::__construct($brand);
}
public function describe(): string
{
return "{$this->brand} with {$this->doors} doors";
}
}
echo (new Car("Tata", 4))->describe();
Tata with 4 doors
Check the relationship
<?php
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
var_dump($dog instanceof Dog);
var_dump($dog instanceof Animal);
echo get_parent_class($dog);
bool(true)
bool(true)
Animal
A Dog can be used anywhere an Animal is expected.
One parent only
A PHP class can extend only one parent. For sharing code across unrelated classes, use traits. For sharing a contract, use interfaces.
Chains of inheritance
A class can extend a class that extends another (Puppy extends Dog extends Animal). Keep such chains short. Deep hierarchies are hard to follow, because the code you need may be spread over many files.
Protected members
protected lets the child use the parent’s property, as $this->name above, while keeping it hidden from the outside.