The Analogy: The Standard Wall Socket
Every wall socket in a building is cut to one published standard: the same hole spacing, the same voltage, the same shape of pin. A kettle, a lamp, a phone charger, and a vacuum cleaner are wildly different machines inside, but each ends in a plug that matches the socket. The building's wiring does not know or care what is on the other end of the plug -- it guarantees the shape of the connection and nothing more. Any appliance that presents the right plug can draw power; anything that does not, cannot, no matter how clever it is inside.
That published standard is an interface. It is a contract that says "to plug into this system, you must provide exactly these methods with exactly these shapes" -- and says nothing about how you provide them. A class that implements an interface is an appliance that has fitted the standard plug: it promises to answer every method the interface lists. The wiring -- the code that consumes the interface -- can then work with any implementer at all, because it depends only on the guaranteed connection, never on the machine behind it. This is the deepest form of decoupling in object-oriented code: the consumer and the implementer agree on a plug and are otherwise strangers.
Because the socket standard is about the connection and not the innards, one appliance can meet several standards at once. A modern device might carry both a power plug and a data plug -- two independent standards, both satisfied by the one device. A PHP class can likewise implements many interfaces, promising to fulfil each contract, whereas it can only extends one parent. Interfaces are how PHP gets the flexibility of multiple "can-do" roles without the tangle of multiple inheritance: a class is one kind of thing (its parent) but can play many roles (its interfaces).
The failure mode is the plug that fits the socket but lies about what it does. Imagine an appliance with a correctly shaped plug whose internal wiring is reversed -- it mates perfectly, draws power, and quietly destroys itself and maybe the circuit. It satisfied the shape of the contract while betraying its intent. In code this is a class that implements an interface's method signatures but violates their meaning: a Comparator that claims to return negative, zero, or positive but sometimes throws, or a Repository::save that returns success without saving. The type checker is satisfied because the shapes match, so the failure surfaces only at runtime, far from the class that caused it. An interface guarantees the shape of a method, never its honesty -- that part is on the implementer.
Syntax or Core Structure
An interface declares method signatures with no bodies. A class states implements and must define every listed method. Code can then type-hint the interface and accept any implementer.
<?php
declare(strict_types=1);
interface Shape {
public function area(): float;
}
class Circle implements Shape {
public function __construct(private float $r) {}
public function area(): float { return 3.14 * $this->r * $this->r; }
}
class Square implements Shape {
public function __construct(private float $side) {}
public function area(): float { return $this->side * $this->side; }
}
function printArea(Shape $s): void {
printf("%s -> %.2f\n", $s::class, $s->area());
}
printArea(new Circle(2.0));
printArea(new Square(3.0));
Output:
Circle -> 12.56
Square -> 9.00
printArea accepts anything that is a Shape, without knowing or caring which class. Circle computes its area one way and Square another, yet both satisfy the one contract, so the function treats them interchangeably -- this is polymorphism. The interface guarantees only that area(): float exists; the two classes share no code and no parent, they simply both fit the plug. Note the areas use a deliberately simple 3.14 for the circle, giving 12.56 for radius 2, and the square is 3 * 3 = 9.00.
Technical Depth: Interfaces, Abstract Classes, and Multiple Roles
Interface versus abstract class
Both define a contract subclasses must meet, but they differ in what they can carry and how many a class may take on. The table lays out the choice.
| Aspect | Interface | Abstract class |
|---|---|---|
| Method bodies | None (pure signatures) | Yes, shared implementations allowed |
| Properties | Only constants | Full properties, any visibility |
| How many per class | Many (implements A, B, C) | One (extends a single parent) |
| Models | A role the class can play | A kind the class is |
The rule of thumb: reach for an interface when you are describing a capability that unrelated classes might share (Jsonable, Comparable, Countable), and an abstract class when you have real shared code plus a common identity for a family of related types. They are not rivals -- a common pattern is an interface implemented by an abstract base that provides default behaviour, with concrete subclasses under it.
Implementing several interfaces
A class can promise many contracts at once. Here Product is both Jsonable and Identifiable, so code that wants either capability accepts it.
<?php
declare(strict_types=1);
interface Jsonable { public function toJson(): string; }
interface Identifiable { public function id(): int; }
class Product implements Jsonable, Identifiable {
public function __construct(private int $id, private string $name) {}
public function id(): int { return $this->id; }
public function toJson(): string {
return json_encode(['id' => $this->id, 'name' => $this->name]);
}
}
$p = new Product(7, 'Widget');
var_dump($p instanceof Jsonable);
var_dump($p instanceof Identifiable);
echo $p->toJson(), "\n";
echo $p->id(), "\n";
Output:
bool(true)
bool(true)
{"id":7,"name":"Widget"}
7
Product satisfies two independent contracts, so $p instanceof Jsonable and $p instanceof Identifiable are both true, and a function type-hinted for either interface accepts it. This is the flexibility interfaces buy that single inheritance cannot: the roles are orthogonal, and a class opts into exactly the ones it can honour. The instanceof operator asks whether an object plays a given role, which is the clean way to check a capability before using it.
Interface constants
An interface cannot hold properties, but it can hold constants -- useful for values that are part of the contract itself, such as status codes every implementer shares. Implementers reach them with self:: and outside code with the interface name.
<?php
declare(strict_types=1);
interface HttpStatus {
public const OK = 200;
public const NOT_FOUND = 404;
public function status(): int;
}
class OkResponse implements HttpStatus {
public function status(): int { return self::OK; }
}
class MissingResponse implements HttpStatus {
public function status(): int { return self::NOT_FOUND; }
}
printf("ok = %d\n", (new OkResponse())->status());
printf("missing = %d\n", (new MissingResponse())->status());
printf("constant = %d\n", HttpStatus::NOT_FOUND);
Output:
ok = 200
missing = 404
constant = 404
The constants belong to the contract, so every implementer sees the same OK and NOT_FOUND values, and outside code can reference HttpStatus::NOT_FOUND without an instance. This keeps shared, contract-level values in one authoritative place. For a fixed set of named values like this, an enum (covered later) is often an even better fit, but interface constants remain the right tool when the values must live alongside a behavioural contract.
Real World Example: A Pluggable Notifier
A common need is to send the same message over several channels -- email, SMS, push -- without the sending code knowing which. An interface Channel fixes the one method send, each channel implements it its own way, and a Notifier holds a list of channels and broadcasts to all of them. Adding a new channel later means writing one class; the Notifier never changes.
<?php
declare(strict_types=1);
interface Channel {
public function send(string $to, string $body): string;
}
class EmailChannel implements Channel {
public function send(string $to, string $body): string {
return sprintf('[email] to=%s len=%d', $to, strlen($body));
}
}
class SmsChannel implements Channel {
public function send(string $to, string $body): string {
$trimmed = substr($body, 0, 10);
return sprintf('[sms] to=%s body=%s', $to, $trimmed);
}
}
class Notifier {
/** @param Channel[] $channels */
public function __construct(private array $channels) {}
public function broadcast(string $to, string $body): void {
foreach ($this->channels as $c) {
echo $c->send($to, $body), "\n";
}
}
}
$n = new Notifier([new EmailChannel(), new SmsChannel()]);
$n->broadcast('user@example.com', 'Your order has shipped');
Output:
[email] to=user@example.com len=22
[sms] to=user@example.com body=Your order
The Notifier depends only on the Channel interface, so it broadcasts over any mix of channels with one loop. The email channel reports the body length -- Your order has shipped is 22 characters -- while the SMS channel truncates to the first 10 characters, Your order. Because both satisfy the contract, the Notifier treats them identically; a PushChannel could join the list tomorrow with no change to the broadcasting code. This is programming to an interface, and it is the backbone of testable, extensible design.
The design is genuinely good, but it hides a real flaw in its error handling -- or rather its absence. broadcast assumes every send succeeds; the interface's return type is a bare string, with no way to signal that a channel failed. If the SMS provider is down, SmsChannel::send has no honest way to report it within the contract as written -- it can only return a misleading success string or throw, and the Notifier catches nothing, so one failing channel aborts the whole broadcast and the channels after it never run. A production contract would return a result object or define which exceptions send may throw, and broadcast would isolate each channel so one failure does not silence the rest. The interface shaped the happy path cleanly but never specified what failure looks like, which is the most commonly omitted half of an interface contract. It is worth stressing how quietly this bites: because the type checker only sees that every send returns a string, the design looks complete and passes review, yet the first real outage reveals that a whole class of behaviour -- partial failure -- was never modelled at all. Designing the failure path into an interface from the start is far cheaper than retrofitting it once callers everywhere assume the happy path.
Common Mistakes
- Implementing the signatures but breaking the intent. An interface guarantees method shapes, not their meaning. A class whose
save()returns success without saving satisfies the type checker and fails at runtime, far from the cause.
- Putting too much in one interface. A fat interface forces implementers to define methods they do not need, often stubbing them to throw. Prefer small, focused interfaces that describe one capability each.
- Type-hinting a concrete class where an interface belongs. Depending on
EmailChannelinstead ofChannelwelds the caller to one implementation and blocks substitution, including test doubles. Hint the interface.
- Forgetting that interface methods are implicitly public. You cannot declare an interface method
protectedorprivate; every method an interface lists is part of the public contract by definition.
- Confusing
implementswithextends. A classextendsone parent class butimplementsany number of interfaces. Trying toextendstwo classes is a fatal error; multiple roles come from interfaces.
- Declaring properties in an interface. Interfaces may hold only constants, not properties. State belongs in the implementing class; the interface describes behaviour.
- Skipping
instanceofand casting blindly. Assuming an object implements an interface and calling its methods without checking leads to errors when a non-implementer slips through. Verify withinstanceofwhen the type is not already guaranteed.
- Not defining failure in the contract. An interface that specifies only the happy path leaves implementers to invent their own error signalling. Decide up front whether methods return a result type or throw declared exceptions.
- Versioning an interface by adding methods. Adding a method to a published interface breaks every existing implementer. Introduce a new interface, or provide the method through a default in an abstract base, rather than expanding a contract others depend on.
Best Practices
- Depend on interfaces, not concrete classes, wherever a collaborator could reasonably vary -- it is what makes code testable and swappable.
- Keep interfaces small and role-focused; a class can implement several narrow interfaces rather than one that does everything.
- Name interfaces for the capability they describe --
Jsonable,Comparable,Channel-- so a class's roles read clearly at theimplementsline.
- Decide and document what failure looks like in the contract: which exceptions may be thrown, or what a result type conveys.
- Use an abstract class beneath an interface when several implementers share real code, keeping the interface as the public contract.
- Check roles with
instanceofwhen a value's type is not already guaranteed by a hint, before relying on interface methods.
- Prefer many specific interfaces over one general one, so implementers opt into exactly the capabilities they can honour.
- Treat a published interface as frozen; extend behaviour through new interfaces rather than by adding methods that break existing implementers.
Practice Exercises
- Define a
Comparableinterface withcompareTo(self $other): int. Implement it on aVersionclass that compares semantic version strings, and write a function that sorts an array of versions using it.
- Create a
Cacheinterface withget(string $key): ?stringandset(string $key, string $value): void. Provide anArrayCacheand aNullCacheimplementation, and show a service using either through the interface.
- Give a
Reportclass two interfaces,PrintableandExportable, and write two functions each hinting one interface. Confirm withinstanceofthat the object satisfies both.
- Extend the notifier so
Channel::sendreturns a small result object with a success flag and message, and makebroadcastcontinue past a failing channel while collecting the results.