Inheritance
Inheritance lets you build a new class on top of an existing one. The new class gets all the properties and methods of its parent and can add its own or change the inherited ones.
extends
A child class is declared with the extends keyword:
<?php
class Animal
{
public function __construct(protected string $name) {}
public function describe(): string
{
return "{$this->name} is an animal";
}
}
class Dog extends Animal
{
public function bark(): string
{
return "{$this->name}: Woof!";
}
}
$dog = new Dog('Rex');
echo $dog->describe(), "\n"; // Rex is an animal
echo $dog->bark(); // Rex: Woof!Dog has no constructor or describe() method of its own — they come from Animal.
protected
The protected modifier sits between public and private: the property is not accessible from outside, but it is accessible in the class itself and in its children. If $name were private, the bark() method could not read it.
Overriding methods
A child may declare a method with the same name — then its version is the one that gets called. parent:: lets you call the parent's version:
<?php
class Cat
{
public function sound(): string
{
return 'Meow';
}
}
class Kitten extends Cat
{
public function sound(): string
{
return parent::sound() . '-meow';
}
}
echo (new Kitten())->sound(); // Meow-meowPolymorphism
Code can treat objects of different classes the same way as long as they share a method. Which version of the method runs depends on the object itself:
<?php
class Animal
{
public function sound(): string
{
return '...';
}
}
class Cat extends Animal
{
public function sound(): string
{
return 'Meow';
}
}
class Dog extends Animal
{
public function sound(): string
{
return 'Woof';
}
}
foreach ([new Cat(), new Dog(), new Animal()] as $animal) {
echo $animal->sound(), "\n";
}The loop does not need to know whether it has a cat or a dog.
Checking the type
The instanceof operator checks whether an object belongs to a class. An object of a child class also counts as an object of the parent:
<?php
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
var_dump($dog instanceof Dog); // bool(true)
var_dump($dog instanceof Animal); // bool(true)A common mistake
Use inheritance only when the child really is a kind of the parent: a dog is an animal. Do not inherit from a class just to borrow a couple of its methods — it makes the program harder to follow.