Polymorphism
suggest changePolymorphism means that one piece of code can work with values of different types, and each type supplies its own behavior. You write $shape->area() once, and at runtime PHP calls Circle::area(), Square::area() or whatever the object's actual class defines.
The calling code depends only on a contract (an interface, an abstract class or simply "has a method called area()"), not on concrete classes. New types can be added without changing the code that uses them.
This article covers:
- subtype polymorphism with interfaces and abstract classes
- replacing
switchandinstanceofchains with polymorphic methods - the Liskov substitution principle: what makes a subtype safe to use
- duck typing and callables
- polymorphic enums
- PHP's built-in polymorphic interfaces:
Stringable,Countable,IteratorAggregate,JsonSerializable - polymorphic static factories with
static - emulating method overloading
- generics with
@templatedocblocks - the null object pattern
Related topics: Inheritance, Overriding, Interfaces, Abstract Classes, Composition and delegation, Late static binding and Enums.
Polymorphism with interfaces
An interface declares what an object can do. Any class that implements it can be passed where the interface is expected:
<?php
interface Shape
{
public function name(): string;
public function area(): float;
}
final class Circle implements Shape
{
public function __construct(private float $radius) {}
public function name(): string
{
return 'circle';
}
public function area(): float
{
return M_PI * $this->radius ** 2;
}
}
final class Rectangle implements Shape
{
public function __construct(private float $width, private float $height) {}
public function name(): string
{
return 'rectangle';
}
public function area(): float
{
return $this->width * $this->height;
}
}
final class Triangle implements Shape
{
public function __construct(private float $base, private float $height) {}
public function name(): string
{
return 'triangle';
}
public function area(): float
{
return $this->base * $this->height / 2;
}
}
/** @param Shape[] $shapes */
function totalArea(array $shapes): float
{
$total = 0.0;
foreach ($shapes as $shape) {
printf("%-10s %8.2f\n", $shape->name(), $shape->area());
$total += $shape->area();
}
return $total;
}
$shapes = [new Circle(1.5), new Rectangle(3, 4), new Triangle(6, 2)];
printf("%-10s %8.2f\n", 'total', totalArea($shapes));
Output:
circle 7.07
rectangle 12.00
triangle 6.00
total 25.07
totalArea() never mentions Circle, Rectangle or Triangle. It calls name() and area() and PHP picks the implementation based on the class of each object. This is called dynamic dispatch (or dynamic binding): the method is chosen at runtime, from the object, not from the declared type of the variable.
Adding a Hexagon means writing one new class. totalArea() doesn't change.
The Shape type declaration is checked when the function is called. Passing an object that doesn't implement the interface fails immediately, even if it happens to have the right methods:
<?php
interface Shape
{
public function area(): float;
}
final class Blob
{
public function area(): float
{
return 1.0;
}
}
function describe(Shape $shape): string
{
return 'area ' . $shape->area();
}
try {
echo describe(new Blob()), "\n";
} catch (TypeError $e) {
// the message also says where describe() was called from; drop that part
echo get_class($e), ': ', preg_replace('/, called in .*/', '', $e->getMessage()), "\n";
}
Output:
TypeError: describe(): Argument #1 ($shape) must be of type Shape, Blob given
PHP's interfaces are nominal: a class is a Shape only if it says implements Shape.
Polymorphism with abstract classes
An abstract class is a contract with shared code. Subclasses fill in the missing parts and inherit the rest. A common pattern is the template method: the base class defines the algorithm and calls abstract methods for the steps that vary:
<?php
abstract class Report
{
/** @param array<string, int> $data */
public function __construct(protected array $data) {}
// the template method: same steps for every report
final public function render(): string
{
return $this->header() . $this->body() . $this->footer();
}
abstract protected function header(): string;
abstract protected function row(string $label, int $value): string;
protected function body(): string
{
$out = '';
foreach ($this->data as $label => $value) {
$out .= $this->row($label, $value);
}
return $out;
}
protected function footer(): string
{
return '';
}
}
final class CsvReport extends Report
{
protected function header(): string
{
return "label,value\n";
}
protected function row(string $label, int $value): string
{
return "$label,$value\n";
}
}
final class MarkdownReport extends Report
{
protected function header(): string
{
return "| label | value |\n|---|---:|\n";
}
protected function row(string $label, int $value): string
{
return "| $label | $value |\n";
}
protected function footer(): string
{
return '| **total** | ' . array_sum($this->data) . " |\n";
}
}
$data = ['apples' => 12, 'pears' => 7];
foreach ([new CsvReport($data), new MarkdownReport($data)] as $report) {
echo $report->render(), "\n";
}
Output:
label,value
apples,12
pears,7
| label | value |
|---|---:|
| apples | 12 |
| pears | 7 |
| **total** | 19 |
render() is declared in Report, but the $this->header() and $this->row() calls inside it go to the subclass. $this always refers to the actual object, so a call from the parent's code reaches the child's override. MarkdownReport also overrides the optional footer() hook. See Overriding for the rules on overriding methods and calling parent::.
Prefer an interface as the type that callers depend on, and use an abstract class only as an optional helper for implementations. A class can implement many interfaces but extend only one class; see Inheritance.
Replacing conditionals with polymorphism
Code that switches on a type tag is the most common sign that polymorphism is missing:
<?php
function shippingCost(array $order): float
{
return match ($order['method']) {
'standard' => 5.0,
'express' => 5.0 + $order['weight'] * 1.5,
'pickup' => 0.0,
default => throw new InvalidArgumentException("unknown method {$order['method']}"),
};
}
function deliveryDays(array $order): int
{
return match ($order['method']) {
'standard' => 5,
'express' => 1,
'pickup' => 0,
default => throw new InvalidArgumentException("unknown method {$order['method']}"),
};
}
$order = ['method' => 'express', 'weight' => 4.0];
echo shippingCost($order), ' / ', deliveryDays($order), " days\n";
Output:
11 / 1 days
Every function that cares about the shipping method repeats the same match. Adding a new method means finding and updating all of them. Move each branch into its own class instead:
<?php
interface ShippingMethod
{
public function cost(float $weight): float;
public function days(): int;
}
final class Standard implements ShippingMethod
{
public function cost(float $weight): float { return 5.0; }
public function days(): int { return 5; }
}
final class Express implements ShippingMethod
{
public function __construct(private float $perKg = 1.5) {}
public function cost(float $weight): float { return 5.0 + $weight * $this->perKg; }
public function days(): int { return 1; }
}
final class Pickup implements ShippingMethod
{
public function cost(float $weight): float { return 0.0; }
public function days(): int { return 0; }
}
final class Order
{
public function __construct(
public readonly float $weight,
public readonly ShippingMethod $shipping,
) {}
public function summary(): string
{
return sprintf(
'%s: %.2f, %d days',
$this->shipping::class,
$this->shipping->cost($this->weight),
$this->shipping->days(),
);
}
}
// the only place that maps a string to a class
function shippingFrom(string $name): ShippingMethod
{
return match ($name) {
'standard' => new Standard(),
'express' => new Express(),
'pickup' => new Pickup(),
default => throw new InvalidArgumentException("unknown method $name"),
};
}
foreach (['standard', 'express', 'pickup'] as $name) {
echo (new Order(4.0, shippingFrom($name)))->summary(), "\n";
}
Output:
Standard: 5.00, 5 days
Express: 11.00, 1 days
Pickup: 0.00, 0 days
There is still one match, in the factory that turns user input into an object. That's unavoidable: something has to decide which class to create. But it happens once, at the boundary, and the rest of the code works with ShippingMethod objects.
The same applies to instanceof chains. If you find yourself writing:
if ($shape instanceof Circle) {
$area = M_PI * $shape->radius ** 2;
} elseif ($shape instanceof Rectangle) {
$area = $shape->width * $shape->height;
}
the code should be a method on the classes. instanceof is fine for optional capabilities (does this object also implement Countable?) and at system boundaries, but not as a replacement for dispatch.
The Liskov substitution principle
Polymorphism only works if every implementation can stand in for the contract. This is the Liskov substitution principle (LSP): code written against a type must keep working when given any subtype.
PHP enforces the signature part of it. An overriding method may accept wider parameter types (contravariance) and return narrower types (covariance), but not the other way around:
<?php
interface Animal {}
final class Dog implements Animal {}
interface Shelter
{
public function adopt(string $name): Animal;
}
final class DogShelter implements Shelter
{
// covariant return: Dog is narrower than Animal - allowed
// contravariant parameter: string|int is wider than string - allowed
public function adopt(string|int $name): Dog
{
return new Dog();
}
}
function adoptOne(Shelter $shelter): void
{
echo get_class($shelter->adopt('Rex')), "\n";
}
adoptOne(new DogShelter());
Output:
Dog
Declaring adopt(Dog $name) or a return type of object would be a compile-time fatal error, because callers of Shelter could then be broken. See Overriding for the full signature rules.
PHP can't check behavior, though. The classic violation is a square that extends a rectangle:
<?php
class Rectangle
{
public function __construct(protected int $width, protected int $height) {}
public function setWidth(int $width): void { $this->width = $width; }
public function setHeight(int $height): void { $this->height = $height; }
public function area(): int { return $this->width * $this->height; }
}
class Square extends Rectangle
{
public function __construct(int $side)
{
parent::__construct($side, $side);
}
// keep the sides equal
public function setWidth(int $width): void { $this->width = $this->height = $width; }
public function setHeight(int $height): void { $this->width = $this->height = $height; }
}
function stretch(Rectangle $r): void
{
$r->setWidth(5);
$r->setHeight(4);
echo get_class($r), ': expected 20, got ', $r->area(), "\n";
}
stretch(new Rectangle(1, 1));
stretch(new Square(1));
Output:
Rectangle: expected 20, got 20
Square: expected 20, got 16
Every signature matches, but Square breaks the assumption that setting the width doesn't change the height. Code written for Rectangle silently produces wrong results. A subtype must keep the promises of its parent: accept at least the same inputs, not throw new kinds of exceptions for them, and maintain the same invariants. If it can't, it shouldn't be a subtype. Here, immutable shapes or a common Shape interface with no setters avoid the problem.
Duck typing
Without a type declaration, PHP doesn't check anything until you call the method. Any object that has the method works. This is duck typing: "if it quacks like a duck, it's a duck":
<?php
final class Duck
{
public function speak(): string { return 'Quack'; }
}
final class Robot
{
public function speak(): string { return 'Beep'; }
}
final class Rock {}
function makeItSpeak(object $thing): string
{
if (!method_exists($thing, 'speak')) {
return get_class($thing) . ' cannot speak';
}
return get_class($thing) . ' says ' . $thing->speak();
}
foreach ([new Duck(), new Robot(), new Rock()] as $thing) {
echo makeItSpeak($thing), "\n";
}
Output:
Duck says Quack
Robot says Beep
Rock cannot speak
Duck typing is flexible, but errors show up late and tools can't help you. method_exists() also returns true for private methods, and misses methods handled by __call(). In application code, an interface is almost always better. Duck typing is still useful for small glue code and for working with classes you don't control.
Callables
The most useful form of duck typing in PHP is the callable and Closure type. Functions, closures, invokable objects and methods are all interchangeable:
<?php
final class Exclaim
{
public function __invoke(string $s): string
{
return $s . '!';
}
}
final class Text
{
public static function shout(string $s): string
{
return strtoupper($s);
}
}
/** @param list<callable(string): string> $steps */
function pipeline(string $input, callable ...$steps): string
{
foreach ($steps as $step) {
$input = $step($input);
}
return $input;
}
echo pipeline(
' hello world ',
trim(...), // built-in function
fn(string $s) => ucwords($s), // arrow function
Text::shout(...), // static method
new Exclaim(), // object with __invoke
), "\n";
Output:
HELLO WORLD!
pipeline() doesn't care what kind of callable each step is. For one-method behaviors, a closure is often simpler than an interface with a single implementation per class. Composition and delegation shows strategies built both ways.
Polymorphic enums
Enum cases are objects, so enums can have methods and implement interfaces. A match ($this) inside the enum keeps all case-specific behavior in one place, and the enum can be used wherever its interface is expected:
<?php
interface HasLabel
{
public function label(): string;
}
enum Status: string implements HasLabel
{
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
public function label(): string
{
return match ($this) {
self::Draft => 'Draft (not visible)',
self::Published => 'Published',
self::Archived => 'Archived (read only)',
};
}
public function canEdit(): bool
{
return $this !== self::Archived;
}
}
final class Priority implements HasLabel
{
public function __construct(private int $level) {}
public function label(): string
{
return str_repeat('*', $this->level);
}
}
function badge(HasLabel $item): string
{
return '[' . $item->label() . ']';
}
foreach (Status::cases() as $status) {
printf("%-24s edit: %s\n", badge($status), $status->canEdit() ? 'yes' : 'no');
}
echo badge(Status::from('published')), ' ', badge(new Priority(3)), "\n";
Output:
[Draft (not visible)] edit: yes
[Published] edit: yes
[Archived (read only)] edit: no
[Published] [***]
The match in an enum is exhaustive in practice: if you add a case and forget a branch, calling the method on it throws UnhandledMatchError, and static analyzers such as PHPStan report it before that. Use enums when the set of variants is fixed and known up front. Use classes when other code (or other packages) need to add new variants.
Built-in polymorphic interfaces
PHP's own functions and language constructs are polymorphic over a few built-in interfaces. Implementing them makes your objects work with echo, count(), foreach and json_encode():
<?php
final class Playlist implements Countable, IteratorAggregate, JsonSerializable, Stringable
{
/** @var list<string> */
private array $songs;
public function __construct(private string $name, string ...$songs)
{
$this->songs = $songs;
}
public function count(): int
{
return count($this->songs);
}
public function getIterator(): Iterator
{
return new ArrayIterator($this->songs);
}
public function jsonSerialize(): array
{
return ['name' => $this->name, 'songs' => $this->songs];
}
public function __toString(): string
{
return "{$this->name} ({$this->count()} songs)";
}
}
$p = new Playlist('Road trip', 'Highway Star', 'Radar Love', 'Roadrunner');
echo $p, "\n"; // Stringable
echo count($p), "\n"; // Countable
foreach ($p as $i => $song) { // IteratorAggregate
echo " $i: $song\n";
}
echo json_encode($p), "\n"; // JsonSerializable
// the same functions accept built-in types and other objects
foreach ([[1, 2, 3], $p, new ArrayObject(['a', 'b'])] as $thing) {
printf("%-12s count=%d\n", get_debug_type($thing), count($thing));
}
Output:
Road trip (3 songs)
3
0: Highway Star
1: Radar Love
2: Roadrunner
{"name":"Road trip","songs":["Highway Star","Radar Love","Roadrunner"]}
array count=3
Playlist count=3
ArrayObject count=2
count() works the same way on an array, a Playlist and an ArrayObject. Any class with __toString() implements Stringable automatically, even without declaring it, so a string|Stringable parameter accepts it. The ArrayAccess and Iterator interfaces article covers more of these.
Polymorphic static factories
Static methods are inherited too. Inside them, static refers to the class the method was called on, not the class where it was written. This lets a base class define factories and fluent "withers" that return the right subclass:
<?php
abstract class Model
{
protected array $attributes = [];
public static function create(array $attributes): static
{
$model = new static();
$model->attributes = $attributes;
return $model;
}
public function with(string $key, mixed $value): static
{
$copy = clone $this;
$copy->attributes[$key] = $value;
return $copy;
}
abstract public function table(): string;
public function describe(): string
{
return static::class . ' -> ' . $this->table() . ' ' . json_encode($this->attributes);
}
}
final class User extends Model
{
public function table(): string { return 'users'; }
public function isAdmin(): bool { return ($this->attributes['role'] ?? '') === 'admin'; }
}
final class Post extends Model
{
public function table(): string { return 'posts'; }
}
$user = User::create(['name' => 'Ada'])->with('role', 'admin');
$post = Post::create(['title' => 'Hello']);
echo $user->describe(), "\n";
echo $post->describe(), "\n";
var_dump($user->isAdmin()); // with() returned a User, not a Model
Output:
User -> users {"name":"Ada","role":"admin"}
Post -> posts {"title":"Hello"}
bool(true)
With new self() and a self return type, User::create() would try to instantiate the abstract Model and fail. static makes the factory polymorphic. This is late static binding.
Emulating method overloading
Many languages have ad hoc polymorphism through overloading: several methods with the same name and different parameter types. PHP doesn't allow that; declaring two methods with the same name is a fatal error. Instead, a single method accepts a union type and branches on the actual type:
<?php
final class Duration
{
private function __construct(public readonly int $seconds) {}
public static function of(int|string|DateInterval|self $value): self
{
return match (true) {
$value instanceof self => $value,
is_int($value) => new self($value),
$value instanceof DateInterval => new self(
$value->d * 86400 + $value->h * 3600 + $value->i * 60 + $value->s
),
is_string($value) => self::parse($value),
};
}
private static function parse(string $s): self
{
if (!preg_match('/^(\d+)([smh])$/', $s, $m)) {
throw new InvalidArgumentException("bad duration '$s'");
}
return new self((int) $m[1] * ['s' => 1, 'm' => 60, 'h' => 3600][$m[2]]);
}
}
$inputs = [90, '15m', '2h', new DateInterval('P1DT30M'), Duration::of(5)];
foreach ($inputs as $in) {
printf("%-14s => %d s\n", get_debug_type($in), Duration::of($in)->seconds);
}
Output:
int => 90 s
string => 900 s
string => 7200 s
DateInterval => 88200 s
Duration => 5 s
match (true) with type checks is a compact way to write this. Keep it at the edges of your code (constructors, factories, public APIs that accept user input). If the branches start to contain real logic, that's a sign each type should have its own class with a shared interface.
Named constructors are often clearer than overloading: Duration::fromSeconds(90), Duration::fromString('15m'). The caller says what they have, and each method has precise types.
Generics with @template
Parametric polymorphism (generics) means writing code once for any element type: a Collection<User>, a Collection<Post>. PHP has no runtime generics, but static analyzers (PHPStan, Psalm) and IDEs understand @template docblocks:
<?php
/**
* @template T
* @implements IteratorAggregate<int, T>
*/
final class TypedCollection implements IteratorAggregate, Countable
{
/** @var list<T> */
private array $items = [];
/** @param class-string<T> $type */
public function __construct(private string $type) {}
/** @param T $item */
public function add(object $item): void
{
// runtime check, since PHP itself doesn't enforce T
if (!$item instanceof $this->type) {
throw new TypeError(sprintf('expected %s, got %s', $this->type, get_debug_type($item)));
}
$this->items[] = $item;
}
/**
* @template R
* @param callable(T): R $fn
* @return list<R>
*/
public function map(callable $fn): array
{
return array_map($fn, $this->items);
}
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->items);
}
public function count(): int
{
return count($this->items);
}
}
final class User
{
public function __construct(public readonly string $name) {}
}
/** @var TypedCollection<User> $users */
$users = new TypedCollection(User::class);
$users->add(new User('Ada'));
$users->add(new User('Linus'));
print_r($users->map(fn(User $u) => strtoupper($u->name)));
try {
$users->add(new DateTime());
} catch (TypeError $e) {
echo $e->getMessage(), "\n";
}
Output:
Array
(
[0] => ADA
[1] => LINUS
)
expected User, got DateTime
PHP ignores the docblocks at runtime, which is why add() checks the type itself. A static analyzer, however, reports $users->add(new DateTime()) as an error before the code runs, and knows that map() here returns list<string>.
The null object pattern
Polymorphism can also remove null checks. Instead of passing null when there's nothing to do, pass an object that implements the interface and does nothing:
<?php
interface Logger
{
public function log(string $message): void;
}
final class EchoLogger implements Logger
{
public function log(string $message): void
{
echo "[log] $message\n";
}
}
final class NullLogger implements Logger
{
public function log(string $message): void {}
}
final class Importer
{
public function __construct(private Logger $logger = new NullLogger()) {}
public function import(array $rows): int
{
foreach ($rows as $i => $row) {
$this->logger->log("row $i: $row"); // no if ($this->logger !== null)
}
return count($rows);
}
}
echo (new Importer())->import(['a', 'b']), " rows imported quietly\n";
echo (new Importer(new EchoLogger()))->import(['a', 'b']), " rows imported\n";
Output:
2 rows imported quietly
[log] row 0: a
[log] row 1: b
2 rows imported
new in a parameter default value (PHP 8.1+) makes NullLogger the default. PSR-3, the standard logging interface, ships a Psr\Log\NullLogger for exactly this.
Summary
- Polymorphism lets one piece of code call the same method on different types; PHP picks the implementation from the object's class at runtime.
- Depend on interfaces. Use abstract classes for shared implementation and template methods.
- A
matchorinstanceofchain on a type is a sign that the behavior belongs in methods on those types. Keep the one unavoidablematchin a factory at the boundary. - Subtypes must honor their parent's contract (Liskov substitution). PHP checks signatures (covariant returns, contravariant parameters); you must keep the behavior compatible.
- Duck typing (
object,method_exists()) and callables are flexible but unchecked.Closureandcallableare the most practical form. - Enums with methods and interfaces are polymorphic over a fixed set of cases.
- Implement
Stringable,Countable,IteratorAggregateandJsonSerializableto make objects work with built-in functions. - Use
new static()and thestaticreturn type for factories and withers that return the right subclass. - PHP has no overloading. Use union types with
match (true), or better, named constructors. - Generics exist only in docblocks (
@template), checked by static analyzers. - A null object replaces
nullchecks with an implementation that does nothing.