Abstract Classes and Interfaces

8.Abstract Classes and Interfaces

M

In this chapter

We'll learn how interfaces describe what an object can do without saying how, how one class implements several interfaces, how abstract classes share code while leaving some methods for the children, when to use which — and default methods in interfaces, a Java feature that PHP doesn't have (and what PHP uses instead).

17–19 min

The Problem in Real Life

Olivia wants WhatsApp confirmations next to SMS and email. The confirmation code checks the channel in three places: if ($channel === "sms") { ... } elseif ($channel === "email") { ... } — once to send, once to format the message, once to log it.

Mia adds a WhatsApp branch. The first customer who chooses WhatsApp gets her confirmation, but the log says "unknown channel" and the message has no greeting. She updated two of the three places.

M

Every new channel means finding every if. Isn't there a way to say "anything that can send a confirmation"?

Mia

An if for Every Channel vs. One Contract

if chains everywhere

Code that checks "which channel?" in many places has to be found and changed in all of them for every new channel.

A contract

An interface says "anything that can send a message has send()". Code depends on the promise, not on SMS or email.

Shared code, missing pieces

An abstract class gives children the shared steps and leaves the different steps for each child to fill in.

Abstract Classes and Interfaces

Describing what, not how: sometimes code doesn't care which class it gets, only what it can do. PHP has two tools for that:

  • Interfaces: a list of methods a class promises to have — a contract, with no code.
  • Implementing interfaces: one class, any number of contracts.
  • Abstract classes: a parent class with shared code and some methods left empty.
  • Default methods: Java's interfaces-with-code, and why PHP uses traits instead.

Interfaces: interface Notifier { public function send(string $to, string $message): void; } declares a contract: any class that implements Notifier must have a public send() method with that signature. An interface contains no code and no properties — only method signatures (always public) and constants. You can't create an object from it ("Cannot instantiate interface Notifier"); it's a type. Now the confirmation code can accept Notifier $notifier and call $notifier->send(...) without knowing whether it's SMS, email or WhatsApp. Adding WhatsApp means writing one new class that implements Notifier — no if to find, anywhere. That's Mia's fix. The diagram below shows one contract with three classes behind it.

One contract, many implementations

interface Notifier

the contract: send(string $to, string $message)

implements

SmsNotifier

sends a text

EmailNotifier

sends an email

WhatsAppNotifier

sends a WhatsApp message

used through the interface

confirm(Notifier $n)

works with every one of them — and with the next channel too

Mia's bug: an if for every channel, in every place
<?php
function sendConfirmation(string $channel, string $to): string
{
if ($channel === "sms") {
return "SMS to $to";
} elseif ($channel === "email") {
return "Email to $to";
} elseif ($channel === "whatsapp") { // added here...
return "WhatsApp to $to";
}
return "unknown channel";
}
function logLine(string $channel): string
{
if ($channel === "sms" || $channel === "email") { // ...but not here
return "logged $channel";
}
return "unknown channel";
}
echo sendConfirmation("whatsapp", "+447700900456"), " / ", logLine("whatsapp"), "\n";
// WhatsApp to +447700900456 / unknown channel
The fix: an interface, and one class per channel
<?php
declare(strict_types=1);
interface Notifier
{
public function send(string $to, string $message): string;
}
class SmsNotifier implements Notifier
{
public function send(string $to, string $message): string
{
return "SMS to $to: $message";
}
}
class WhatsAppNotifier implements Notifier // the new channel: one new class
{
public function send(string $to, string $message): string
{
return "WhatsApp to $to: $message";
}
}
function confirm(Notifier $notifier, string $to): string // works with ANY Notifier
{
return $notifier->send($to, "Your booking is confirmed.");
}
echo confirm(new SmsNotifier(), "+447700900123"), "\n";
echo confirm(new WhatsAppNotifier(), "+447700900456"), "\n";
// SMS to +447700900123: Your booking is confirmed.
// WhatsApp to +447700900456: Your booking is confirmed.

Implementing interfaces: class SmsNotifier implements Notifier { ... } signs the contract. If a method is missing or has the wrong signature, PHP refuses to load the class, so a half-done WhatsApp class can't reach production. A class can implement several interfaces — class SmsNotifier implements Notifier, Loggable — which is how PHP gives one class several "can do" types without multiple inheritance (chapter 7). Interfaces can extend other interfaces, too. $x instanceof Notifier checks the contract, and a parameter typed with an interface accepts every class that implements it. PHP's own interfaces work the same way: Countable makes count($object) work, and JsonSerializable controls json_encode() (Act 19).

Several interfaces, and interface constants
<?php
declare(strict_types=1);
interface Notifier
{
public function send(string $to, string $message): string;
}
interface HasCost
{
public const string CURRENCY = "GBP";
public function costPence(): int;
}
class SmsNotifier implements Notifier, HasCost // two contracts
{
public function send(string $to, string $message): string
{
return "SMS to $to";
}
public function costPence(): int
{
return 4;
}
}
$sms = new SmsNotifier();
var_dump($sms instanceof Notifier, $sms instanceof HasCost); // bool(true) bool(true)
echo $sms->costPence(), " pence (", HasCost::CURRENCY, ")\n"; // 4 pence (GBP)
try {
new Notifier();
} catch (Error $e) {
echo $e->getMessage(), "\n"; // Cannot instantiate interface Notifier
}

Abstract classes: an abstract class is a parent that can't be instantiated itself, and that may declare abstract methods — methods with a signature but no body, which every child must implement. Unlike an interface, it can also contain normal methods, properties and a constructor. That makes it right when several classes share real code. A typical example: every notifier formats the message the same way and logs every send, but the actual sending differs. The abstract class does the shared steps in one method and calls an abstract deliver() that each child fills in. That pattern is called the template method. The diagram below follows one call through the template method.

The template method: shared steps, one step left to the child

$email->send("clare@example.com", "See you at 9:30.")

calls the method written in the abstract parent

1

BaseNotifier::send() — shared

adds the shop name, will log the send

2

$this->deliver($to, $text) — abstract

BaseNotifier has no body for this step

3: PHP runs the child's version

EmailNotifier::deliver() — the child's part

the only code that differs per channel

An abstract class: shared steps, one missing piece
<?php
declare(strict_types=1);
abstract class BaseNotifier
{
public array $log = [];
public function send(string $to, string $message): void // the template: same for all
{
$text = "Tom's Barbershop: " . $message;
$this->deliver($to, $text); // the part that differs
$this->log[] = static::class . " → $to";
}
abstract protected function deliver(string $to, string $text): void; // no body
}
class EmailNotifier extends BaseNotifier
{
protected function deliver(string $to, string $text): void
{
echo "Email to $to: $text\n";
}
}
$email = new EmailNotifier();
$email->send("clare@example.com", "See you at 9:30.");
echo $email->log[0], "\n";
// Email to clare@example.com: Tom's Barbershop: See you at 9:30.
// EmailNotifier → clare@example.com
try {
new BaseNotifier();
} catch (Error $e) {
echo $e->getMessage(), "\n"; // Cannot instantiate abstract class BaseNotifier
}

Interface or abstract class: use an interface to describe a capability — what code can rely on — especially when unrelated classes should share it. Use an abstract class to share code between closely related classes. They combine well, and that's the usual design: code depends on the interface, and an abstract class implements it with the shared parts. A class can implement many interfaces but extend only one class, so prefer interfaces for types; don't make an abstract class just to have a type. Since PHP 8.4 interfaces can also declare properties (with hooks — Act 12). The table below compares the two.

Table — Interface vs. abstract class
QuestionInterfaceAbstract class
Can contain code?No (only signatures and constants)Yes: normal methods and properties
Constructor?NoYes
How many per class?Any number (implements A, B, C)One (extends)
Can be instantiated?NoNo
Use it forA capability: what code can rely onShared code between related classes
Methods with a default bodyNot in PHP (Java 8 and C# 8 have them)Yes

Default methods in interfaces — not in PHP: since Java 8, a Java interface can contain default methods: methods with a body, which every implementing class gets for free unless it overrides them. C# 8 added the same. PHP doesn't support that: an interface method never has a body. When several classes implementing an interface should share code, PHP uses either an abstract class that implements the interface, or a trait (the next chapter), which copies methods into each class. The result is the same — a contract plus shared code — split into two pieces instead of one.

Java: a default method in an interface (not in PHP)
// Java 8+ — an interface method with a body
interface Notifier {
void send(String to, String message);
default void sendConfirmation(String to) { // every Notifier gets this for free
send(to, "Your booking is confirmed.");
}
}
// In PHP, an interface method can't have a body. Put sendConfirmation()
// in an abstract class that implements Notifier, or in a trait (chapter 9).

Key Takeaway

An interface is a contract: method signatures with no code, which a class signs with implements; code that depends on the interface works with every implementation, so a new channel is one new class instead of edits to every if. A class can implement many interfaces. An abstract class can't be instantiated, shares real code, and forces children to implement its abstract methods (the template method pattern). Use interfaces for types and abstract classes for shared code. PHP interfaces have no default methods (Java 8, C# 8); use an abstract class or a trait.

Why This Matters

Interfaces are how code stays open to new cases without being edited: SMS, email, WhatsApp, a test double that sends nothing (chapter 12) — all through one Notifier type. Every new case is a new class, and the code that uses them doesn't change.

Almost everything in a framework is reached through interfaces: Laravel's mailers, caches, queues and loggers are contracts with several implementations, chosen in configuration. Reading implements and abstract classes is reading the skeleton of every modern PHP library.

Every channel is now a Notifier, and WhatsApp is one small class. While writing the notifier classes, Mia notices the same three things in Booking, Customer and Barber too: a createdAt property, a touch() method and a log() method — copied into each class. They have nothing else in common, so inheritance makes no sense. That's the next chapter: traits.