Inheritance and Overriding

7.Inheritance and Overriding

M

In this chapter

We'll learn how a class inherits from another with extends — the five kinds of inheritance (single, multilevel, hierarchical, multiple and hybrid) and which of them PHP supports — how a child overrides a parent's method and calls it with parent::, the rules a child must follow, how final stops inheritance, and why PHP has no multiple inheritance (the diamond problem) and no sealed classes.

24–27 min

The Problem in Real Life

Group bookings arrive: a stag party of six, all at once, with a 10% group discount. Mia copies the 120-line Booking class into a new GroupBooking class and adds the group parts. It works.

A week later, Marcus fixes a bug in Booking::confirm(): it now refuses to confirm a booking in the past. Single bookings get the fix. Group bookings don't — GroupBooking has its own copy of confirm(). It's Act 09's six copies again, this time as classes.

M

A group booking IS a booking, with a few extras. Why do I have to copy all of Booking to say that?

Mia

Copying a Class vs. Extending It

Copied classes drift

Two copies of the same 120 lines mean every fix has to be made twice — and one is always forgotten.

Is-a

A group booking is a booking. Inheritance says exactly that: everything Booking has, plus the differences.

One parent only

Python and C++ let a class have several parents. PHP and Java allow one — for a good reason.

Inheritance and Overriding

Building on a class: inheritance lets one class build on another: the new class gets everything the old one has and adds or changes only what's different. This chapter covers:

  • extends: a child class inherits from a parent class.
  • Overriding and parent:: replacing a parent's method, and still using it.
  • The rules: what a child may and may not change, and final.
  • Multiple inheritance and sealed classes: what other languages allow, and why PHP doesn't.

extends: class GroupBooking extends Booking { ... } makes GroupBooking a child class (or subclass) of Booking, its parent class (or superclass). The child inherits every public and protected property and method: a GroupBooking has confirm(), cancel() and summary() without writing them again, and a fix to Booking::confirm() reaches it automatically. The child only adds what's new — a group size, a discount. Inheritance means is-a: a GroupBooking is a Booking, so $group instanceof Booking is true, and a function that accepts Booking $b accepts a group booking too. Use inheritance only when that sentence is true; chapter 12 shows when "has-a" is the better choice.

A child class inherits everything
<?php
declare(strict_types=1);
class Booking
{
public function __construct(protected string $customer, protected int $pricePence) {}
public function confirm(): string
{
return "Confirmed: {$this->customer}";
}
public function price(): int
{
return $this->pricePence;
}
}
class GroupBooking extends Booking
{
// nothing yet: everything comes from Booking
}
$group = new GroupBooking("Stag party: Daniel Brooks", 15000);
echo $group->confirm(), "\n"; // Confirmed: Stag party: Daniel Brooks
var_dump($group instanceof Booking); // bool(true): a group booking IS a booking

The five kinds of inheritance: textbooks and interviews describe inheritance by the shape of the family tree it creates. There are five shapes: single, multilevel, hierarchical, multiple and hybrid. PHP supports the first three directly. The last two need a class with more than one parent, which PHP doesn't allow, so PHP builds them from interfaces and traits instead. Each kind is explained below with its own diagram, and a table at the end puts them side by side.

Single inheritance: one child class extends one parent class — the simplest shape, and the one this chapter started with: class GroupBooking extends Booking. The child gets everything public and protected from its parent and adds its own parts. Every other kind is built from this one step.

Single inheritance — supported in PHP

Booking

parent: customer, price(), confirm()

inherits from

GroupBooking extends Booking

child: + people, its own price()

Multilevel inheritance: a chain of single steps: a child has a parent, which has a parent of its own. StagPartyBooking extends GroupBooking, and GroupBooking extends Booking. The class at the bottom inherits from every level above it. Each constructor that has work to do calls the one above with parent::__construct(), so building a stag party booking runs Booking's part first, then GroupBooking's, then its own — this is called constructor chaining. Keep chains short: three levels is usually the most a reader can hold in mind, and a change at the top ripples down through every level.

Multilevel inheritance — supported in PHP

Booking

level 1: customer, price()

inherits from

GroupBooking extends Booking

level 2: + people, 10% group discount

inherits from

StagPartyBooking extends GroupBooking

level 3: + venue · has everything from levels 1 and 2

Multilevel inheritance and constructor chaining
<?php
declare(strict_types=1);
class Booking
{
public function __construct(public string $customer)
{
echo "Booking part, ";
}
}
class GroupBooking extends Booking
{
public function __construct(string $customer, public int $people)
{
parent::__construct($customer); // level 1 first
echo "GroupBooking part, ";
}
}
class StagPartyBooking extends GroupBooking
{
public function __construct(string $customer, int $people, public string $venue)
{
parent::__construct($customer, $people); // then level 2
echo "StagPartyBooking part\n";
}
}
$stag = new StagPartyBooking("Daniel Brooks", 6, "Tom's back room");
echo "{$stag->customer}, {$stag->people} people, {$stag->venue}\n";
var_dump($stag instanceof Booking); // bool(true): a booking at every level
// Booking part, GroupBooking part, StagPartyBooking part
// Daniel Brooks, 6 people, Tom's back room

Hierarchical inheritance: several children extend the same parent: GroupBooking, GiftBooking and StaffBooking all extend Booking. They share everything in Booking but don't know about each other — a fix in Booking reaches all three. This is the most common shape in real projects, and it's what makes polymorphism (chapter 10) so useful: code written for Booking works with all of its children.

Hierarchical inheritance — supported in PHP

Booking

one parent: shared customer, confirm(), price()

all extend Booking

GroupBooking

+ people

GiftBooking

+ voucher code

StaffBooking

+ staff discount

Hierarchical inheritance: three children, one parent
<?php
declare(strict_types=1);
class Booking
{
public function price(): int { return 2500; }
}
class GroupBooking extends Booking
{
public function price(): int { return 13500; }
}
class GiftBooking extends Booking
{
public function price(): int { return 0; }
}
class StaffBooking extends Booking
{
public function price(): int { return parent::price() - 500; }
}
foreach ([new GroupBooking(), new GiftBooking(), new StaffBooking()] as $b) {
echo get_class($b), " → ", get_parent_class($b), ": ", $b->price(), "\n";
}
// GroupBooking → Booking: 13500
// GiftBooking → Booking: 0
// StaffBooking → Booking: 2000

Multiple inheritance: one child with two or more parents at the same time — a StagParty that is both a GroupBooking and an Event, inheriting code from both. Python and C++ allow it; PHP, Java and C# don't. The reason is the diamond problem, explained in detail further down. In PHP, a class gets "several parents' worth" of types and code another way: it extends one class, implements any number of interfaces (several types) and uses traits (shared code).

Multiple inheritance — NOT supported in PHP

GroupBooking

price(), people

Event

venue, startTime()

two parents

StagParty extends GroupBooking, Event

✗ syntax error in PHP — one parent only

Hybrid inheritance: a mix of the other kinds in one family tree — for example hierarchical at the top (two children of Booking) and multiple at the bottom (a class that extends both of them). Because it contains multiple inheritance, hybrid inheritance is also not possible in PHP, and it's exactly the shape that produces the diamond problem. PHP gets the same design by combining single inheritance with interfaces and traits, as the code below shows: StagParty extends one class, and is an Event through an interface plus a trait.

Hybrid inheritance — NOT supported in PHP (it contains multiple inheritance)

Booking

the shared grandparent

two children

GroupBooking extends Booking

hierarchical part

Event extends Booking

hierarchical part

one child of both

StagParty extends GroupBooking, Event

multiple part ✗ — in PHP: extends GroupBooking implements EventLike, uses a trait

How PHP builds the same design: one parent + interface + trait
<?php
declare(strict_types=1);
class Booking
{
public function price(): int { return 2500; }
}
class GroupBooking extends Booking
{
public function price(): int { return 13500; }
}
interface EventLike // the second "parent" as a type
{
public function venue(): string;
}
trait HasVenue // the second "parent" as shared code
{
public string $venueName = "Tom's back room";
public function venue(): string { return $this->venueName; }
}
final class StagParty extends GroupBooking implements EventLike
{
use HasVenue;
}
$party = new StagParty();
echo $party->price(), " at ", $party->venue(), "\n"; // 13500 at Tom's back room
var_dump($party instanceof Booking, $party instanceof EventLike); // bool(true) bool(true)

The five kinds side by side: the table below puts the five shapes next to each other. The rule to remember: PHP lets a class have many children and a long line of ancestors, but only one parent — everything else comes from interfaces and traits.

Table — The five kinds of inheritance
KindShapePHPExample
SingleOne parent → one childSupportedGroupBooking extends Booking
MultilevelA chain: grandparent → parent → childSupportedStagPartyBooking extends GroupBooking extends Booking
HierarchicalOne parent → several childrenSupportedGroupBooking, GiftBooking, StaffBooking extend Booking
MultipleSeveral parents → one childNot supported: interfaces + traitsStagParty extends GroupBooking, Event ✗
HybridA mix, usually including multipleNot supported: interfaces + traitsThe diamond: Booking → two children → one grandchild ✗

Overriding: a child can override a parent's method by declaring a method with the same name: GroupBooking::price() replaces Booking::price() for group bookings. Often the child doesn't want to replace the whole method, just add to it: parent::price() calls the parent's version from inside the override, and the child adjusts the result. The same goes for constructors: a child with its own constructor must call parent::__construct(...) itself, or the parent's part of the object is never set up. Since PHP 8.3, putting #[\Override] above a method asks PHP to check that the method really overrides something; a typo in the name becomes an error instead of a new, never-called method. (#[...] is an attribute — Act 12.)

Overriding, parent::, and a child constructor
<?php
declare(strict_types=1);
class Booking
{
public function __construct(protected string $customer, protected int $pricePence) {}
public function price(): int
{
return $this->pricePence;
}
}
class GroupBooking extends Booking
{
public function __construct(string $customer, int $pricePence, private int $people)
{
parent::__construct($customer, $pricePence); // set up the Booking part
}
#[\Override]
public function price(): int
{
$full = parent::price() * $this->people; // reuse the parent's version
return $full - intdiv($full * 10, 100); // 10% group discount
}
}
echo (new Booking("Tom Hart", 2500))->price(), "\n"; // 2500
echo (new GroupBooking("Daniel Brooks", 2500, 6))->price(), "\n"; // 13500

The rules a child must follow: a child can be used wherever the parent is expected, so it must not break the parent's promises. PHP enforces part of that. An overriding method can't be less visible than the parent's: a public method can't become protected or private ("Access level to GroupBooking::price() must be public"). Its parameters and return type must stay compatible — the exact rules are called covariance and contravariance (Act 12). Private methods are not inherited at all, so a child can't override them; protected ones are, which is why protected exists (chapter 4).

Overrides can't be less visible
<?php
class Booking
{
public function price(): int
{
return 2500;
}
}
class GroupBooking extends Booking
{
protected function price(): int // public in the parent: not allowed
{
return 13500;
}
}
// Fatal error: Access level to GroupBooking::price() must be public (as in class Booking)

final: final public function confirm() forbids children to override that method: the rule in it must hold for every kind of booking. final class Money forbids inheriting from the class at all, which is right for value objects (chapter 6) and for any class that wasn't designed to be extended. Both are checked when PHP reads the code: "Cannot override final method" and "Class … cannot extend final class". Many PHP developers make classes final by default and remove it only when inheritance is really planned.

final methods and final classes
<?php
class Booking
{
final public function confirm(): string // the rule must hold for every booking
{
return "confirmed";
}
}
class GroupBooking extends Booking
{
public function confirm(): string
{
return "confirmed without checks";
}
}
// Fatal error: Cannot override final method Booking::confirm()

Multiple inheritance — not in PHP: some languages let a class have several parents at once. In Python, class StagParty(GroupBooking, Event) inherits from both; C++ allows it too. Java and C# don't — and neither does PHP: class C extends A, B is a syntax error, and a class has exactly one parent. The reason is the diamond problem. Imagine GroupBooking and Event both inherit from Booking, both override price(), and StagParty inherits from both: which price() does a stag party use? Python answers with a fixed search order, the MRO (method resolution order); C++ makes you choose explicitly. PHP, like Java, avoids the question entirely: one parent for behaviour, plus any number of interfaces (chapter 8) for "can do" promises, and traits (chapter 9) for sharing code. The diagram below shows the diamond.

The diamond problem — why PHP allows only one parent

Booking

price(): the normal price

both extend Booking

GroupBooking

price(): 10% off

Event

price(): + venue fee

inherits from both

StagParty extends GroupBooking, Event

which price()? — Python: MRO order; C++: you choose; PHP and Java: not allowed

Python: multiple inheritance and the MRO (not in PHP)
# Python — a class may have several parents
class Booking:
def price(self): return 2500
class GroupBooking(Booking):
def price(self): return 2250 # 10% off
class Event(Booking):
def price(self): return 3000 # + venue fee
class StagParty(GroupBooking, Event): # two parents: the diamond
pass
print(StagParty().price()) # 2250 — GroupBooking wins: it's listed first
print([c.__name__ for c in StagParty.__mro__])
# ['StagParty', 'GroupBooking', 'Event', 'Booking', 'object']
In PHP, a second parent is a syntax error
<?php
class GroupBooking {}
class Event {}
class StagParty extends GroupBooking, Event {}
// Parse error: syntax error, unexpected token ",", expecting "{"

Sealed classes — not in PHP: final is all or nothing: anyone may extend a class, or nobody may. Java (17+), Kotlin and C#-style languages have a middle ground: a sealed class names exactly which classes may extend it — sealed class Booking permits SingleBooking, GroupBooking — so the compiler knows every possible kind of booking. PHP doesn't support sealed classes (a proposal was turned down in 2022). In PHP you use final on the classes that shouldn't be extended, and enums (Act 12) for a closed set of cases. The table below sums up the chapter.

Table — Inheritance features
FeaturePHPOther languages
Single inheritance (extends)YesJava, C#, Python, C++
Multiple inheritanceNo: interfaces + traits insteadPython (MRO), C++ (virtual inheritance)
Call the parent's methodparent::method()super.method() (Java), super() (Python)
Forbid overriding / extendingfinal method / final classfinal (Java), sealed override / sealed (C#)
Only listed subclassesNo sealed classessealed ... permits (Java 17), sealed (Kotlin)
Check an override exists#[\Override] (8.3)@Override (Java), override (C#, Kotlin)
Java: a sealed class (not in PHP)
// Java 17 — only the listed classes may extend Booking
public sealed class Booking permits SingleBooking, GroupBooking { }
final class SingleBooking extends Booking { }
final class GroupBooking extends Booking { }
// class Raffle extends Booking { } // compile error: not in the permits list

Key Takeaway

class Child extends Parent inherits every public and protected member, so fixes in the parent reach every child; use it only for a true is-a relationship. A child overrides a method by redeclaring it and reaches the original with parent::method() — and must call parent::__construct() itself. Overrides can't reduce visibility and must keep compatible signatures; #[\Override] checks the name. final stops overriding or extending. PHP allows one parent only — no multiple inheritance (Python, C++), avoiding the diamond problem — and has no sealed classes (Java, Kotlin).

Why This Matters

Inheritance turns "a group booking is a booking, plus a discount" into code that says exactly that — and makes every fix to Booking reach every kind of booking. Used for a real is-a relationship, it removes whole classes of copy-paste bugs.

Knowing PHP's limits — one parent, no sealed classes — and the reason behind them (the diamond problem) is what lets you read code from other languages and choose the right PHP tool instead: interfaces and traits, the next two chapters.

GroupBooking extends Booking, and the past-booking fix reaches both. Then Olivia asks for WhatsApp confirmations next to SMS and email. The confirmation code is a long if ($channel === "sms") ... elseif ($channel === "email") ..., and Mia adds WhatsApp to it — in two of the three places that check the channel. That's the next chapter: abstract classes and interfaces.