Encapsulation, Abstraction and Polymorphism

10.Encapsulation, Abstraction and Polymorphism

M

In this chapter

We'll learn the ideas that hold OOP together — encapsulation, abstraction and polymorphism — by replacing an instanceof chain with objects that answer for themselves, and the forms of polymorphism other languages have that PHP doesn't: operator overloading, generics and multiple dispatch.

17–19 min

The Problem in Real Life

The price code has grown a long chain: if ($booking instanceof GroupBooking) { ... } elseif ($booking instanceof StaffBooking) { ... } else { ... }. Gift bookings, added last week, aren't in it — so they fall into the else and are charged the full price.

"Every time the code asks an object what it is, so that it can decide what to do with it," says Marcus, "it's doing the object's job for it."

M

Every booking type has its own price rule. Why does the price code have to know all of them?

Mia

Asking What It Is vs. Telling It What to Do

instanceof chains

Code that checks the class before acting must be updated for every new class — and quietly fails when it isn't.

Rules inside the object

Encapsulation keeps each booking's data and rules together, behind methods.

Same call, right answer

Polymorphism: price() on any booking gives that booking's price — the caller never asks which kind it is.

Encapsulation, Abstraction and Polymorphism

The ideas behind the syntax: chapters 1 to 9 were the tools. OOP is usually summed up in four principles — encapsulation, abstraction, inheritance (chapter 7) and polymorphism. This chapter covers the other three, and the parts of polymorphism PHP doesn't have:

  • Encapsulation: an object guards its own data.
  • Abstraction: code depends on what an object does, not how.
  • Polymorphism: the same call does the right thing for each kind of object.
  • Operator overloading, generics and multiple dispatch: what other languages have, and what PHP does instead.

Encapsulation: an object encapsulates its data: it keeps it private and offers methods that keep it valid (chapter 4). The rules about bookings live in Booking, so a booking can never be in an impossible state, like confirmed after being cancelled. A practical test is the "tell, don't ask" rule: instead of asking an object for its data and deciding outside (if ($booking->status() === "pending") { ... set status ... }), tell it what you want ($booking->confirm()) and let it decide.

Tell, don't ask
<?php
declare(strict_types=1);
class Booking
{
private string $status = "pending";
public function confirm(): void // the rule lives here
{
if ($this->status === "cancelled") {
throw new LogicException("Cancelled bookings can't be confirmed");
}
$this->status = "confirmed";
}
public function status(): string
{
return $this->status;
}
}
$booking = new Booking();
$booking->confirm(); // tell it — don't check its status outside
echo $booking->status(), "\n"; // confirmed

Abstraction: abstraction means showing only what matters and hiding the rest. The Notifier interface (chapter 8) is an abstraction: confirmation code knows that a notifier can send(), and nothing about SMS gateways, email servers or WhatsApp APIs. Every public method is a small abstraction too: $booking->price() hides whether there's a discount, a surcharge or a group size behind it. Good abstractions make code shorter to read and safe to change, because the details can change behind them.

Abstraction vs. encapsulation: these two are easy to mix up, and interviewers love to ask about them. Encapsulation is about protecting: hide the data and let only the object's own methods change it, so it stays valid (private properties, public methods). Abstraction is about simplifying: show only what a user of the object needs and hide how it works (interfaces, clear public methods). They work together — Booking::confirm() is abstraction (callers just say "confirm") built on encapsulation (the status is private and the rule is inside) — but they answer different questions, as the table below shows.

Table — Abstraction vs. encapsulation
QuestionEncapsulationAbstraction
Main ideaProtect the dataHide the details
AnswersWho may change this, and how?What does the user need to know?
PHP toolsprivate / protected, readonly, private(set), methods with rulesInterfaces, abstract classes, well-named public methods
BookBay examplestatus is private; only confirm() and cancel() change itconfirm(Notifier $n) works without knowing SMS from email
Without itAny code can write status = "confirmd"Every caller must know every channel's details

Polymorphism: polymorphism ("many forms") means one call works on objects of different classes, and each object answers in its own way. $booking->price() runs GroupBooking::price() for a group, GiftBooking::price() for a gift and Booking::price() for the rest — PHP picks the method from the object's class at runtime. That replaces Mia's instanceof chain: each class carries its own price rule, and the total is just array_sum(array_map(fn($b) => $b->price(), $bookings)). A new kind of booking brings its own price(), and the total code never changes. Polymorphism works through inheritance and through interfaces alike. And because PHP checks methods at runtime, it also works without any shared type at all — any object with a price() method can be asked — which is called duck typing ("if it walks like a duck…"). Typed interfaces are safer: PHP and your tools check them. The diagram below follows one call to price() through PHP's choice.

One call, the right method: how PHP picks price()

$booking->price()

the code doesn't know which kind of booking it has

1

PHP looks at the object's class

at runtime, when the line runs

2: run that class's method

GroupBooking → GroupBooking::price()

13500

GiftBooking → GiftBooking::price()

0

Booking → Booking::price()

2500

Mia's bug: an instanceof chain
<?php
class Booking {}
class GroupBooking extends Booking {}
class GiftBooking extends Booking {}
function priceOf(Booking $b): int
{
if ($b instanceof GroupBooking) {
return 13500;
} elseif ($b instanceof Booking) {
return 2500; // GiftBooking lands here: no discount
}
return 0;
}
echo priceOf(new GroupBooking()), " ", priceOf(new GiftBooking()), "\n"; // 13500 2500
The fix: polymorphism — each class answers for itself
<?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; // paid by the voucher
}
}
$bookings = [new Booking(), new GroupBooking(), new GiftBooking()];
$total = array_sum(array_map(fn(Booking $b) => $b->price(), $bookings));
echo $total, "\n"; // 16000 — and a new booking type never touches this line

Compile-time vs. runtime polymorphism: textbooks split polymorphism into two kinds by when the method is chosen. Compile-time (or static) polymorphism means the compiler picks the method before the program runs, from the types of the arguments — that's method overloading (chapter 2) and operator overloading, as in Java, C# and C++. Runtime (or dynamic) polymorphism means the method is picked while the program runs, from the object's real class — overriding, as in the diagram above. The matching words are early binding (decided before running) and late binding (decided while running). PHP has only runtime polymorphism: it has no overloading, and even static:: (Act 12) is resolved at runtime. The table below sums it up.

Table — Compile-time vs. runtime polymorphism
Compile-time (static)Runtime (dynamic)
When the method is chosenBefore the program runs (early binding)While it runs (late binding)
Chosen byThe argument typesThe object's actual class
MechanismMethod and operator overloadingOverriding, interfaces
LanguagesJava, C#, C++Java, C#, C++, PHP, Python
In PHPNot supportedSupported: every method call

Operator overloading — not in PHP: in C++, Python and C#, a class can define what operators like +, - or < mean for its objects, so $a + $b on two Money objects returns a new Money. That's operator overloading, a form of polymorphism for operators. PHP doesn't support it for your classes: $a + $b on two objects is a TypeError ("Unsupported operand types: Money + Money"). You write a method instead: $a->plus($b). (A few of PHP's own classes, like GMP for huge numbers, overload operators internally, and < and == compare objects property by property — chapter 13 — but your classes can't define their own operators.)

Operator overloading in Python (not in PHP)
# Python — a class decides what + means for its objects
class Money:
def __init__(self, pence):
self.pence = pence
def __add__(self, other): # called for a + b
return Money(self.pence + other.pence)
total = Money(2500) + Money(250)
print(total.pence) # 2750
PHP: + on objects is a TypeError — use a method
<?php
declare(strict_types=1);
final readonly class Money
{
public function __construct(public int $pence) {}
public function plus(Money $other): Money
{
return new Money($this->pence + $other->pence);
}
}
$a = new Money(2500);
$b = new Money(250);
try {
$sum = $a + $b;
} catch (TypeError $e) {
echo $e->getMessage(), "\n"; // Unsupported operand types: Money + Money
}
echo $a->plus($b)->pence, "\n"; // 2750

Generics — not in PHP: in Java, C#, TypeScript and many others, a class or function can take a type parameter: List<Booking> is a list that only holds bookings, checked by the compiler. That's generics, also called parametric polymorphism. PHP doesn't support generics in the language; an array can't say "array of Booking". PHP developers write the type in a doc comment instead — /** @var list<Booking> */ or a class with @template T — and let PHPStan (Act 21) check it before the code runs. (Laravel's collections are documented exactly this way.)

Generics in Java, and PHP's docblock equivalent
// Java — the compiler knows this list holds only Bookings
List<Booking> day = new ArrayList<>();
day.add(new Booking());
// day.add("Tom"); // compile error
// PHP — no generics in the language; PHPStan reads the doc comment:
// /** @var list<Booking> $day */
// $day = [];
// $day[] = "Tom"; // PHPStan: list<Booking> does not accept string

Multiple dispatch — not in PHP: PHP picks the method to run from one object: the one before the arrow. Languages with multiple dispatch, like Julia (and Common Lisp), pick it from the types of all the arguments, so collide(Asteroid, Ship) and collide(Ship, Ship) can be separate functions under one name. PHP doesn't support that; it's the same limit as method overloading (chapter 2). When the right behaviour depends on two objects, PHP code uses match on the types or a pattern called double dispatch (one object calls back the other). The table below collects every form of polymorphism and where PHP stands.

Table — Forms of polymorphism
FormExamplePHP
Subtype (inheritance, interfaces)$booking->price() on any BookingYes
Duck typingAny object with a price() methodYes, at runtime (no type check)
Method overloadingprice() / price(int) (Java, C#)No (chapter 2)
Operator overloading$a + $b on Money (C++, Python, C#)No: TypeError; use $a->plus($b)
Generics (parametric)List<Booking> (Java, C#, TypeScript)No: @template docblocks + PHPStan
Multiple dispatchcollide(Ship, Asteroid) (Julia)No: match or double dispatch

Key Takeaway

Encapsulation keeps data and rules together behind methods (tell, don't ask). Abstraction exposes what an object does and hides how — interfaces and public methods. Polymorphism lets one call, like $booking->price(), run the right method for each object's class, replacing instanceof chains; PHP also allows duck typing. PHP doesn't support operator overloading (use methods like plus()), generics (use @template docblocks + PHPStan) or multiple dispatch (use match or double dispatch).

Why This Matters

instanceof chains are how code ends up charging a gift voucher the full price: every new kind of object needs every chain updated. Polymorphism turns that around — the new class brings its own behaviour, and the code that uses it stays exactly as it was.

These principles are also the shared vocabulary of every developer conversation about design, in PHP or any other language. Knowing precisely which kinds of polymorphism PHP has — and which it fakes with methods and doc comments — keeps you from looking for operator overloading or generics that aren't there.

Each booking type now answers price() for itself, and gift bookings cost £0. Then a customer changes her phone number, and her reminders for next week still go to the old one. Each Booking stored its own copy of the phone number when it was created, instead of pointing at the customer. How objects should be connected to each other is the next chapter: composition, aggregation, association and dependency.