Covariance, Contravariance and Late Static Binding

4.Covariance, Contravariance and Late Static Binding

M

In this chapter

We'll learn the rules PHP uses when a child class or an implementation changes a method's types — return types may get narrower (covariance), parameter types may get wider (contravariance) — and late static binding: why new self() in a parent's factory built the wrong class, and how static fixes it. Plus generic variance (Kotlin, C#), which PHP doesn't have, and why Java has no late static binding.

16–18 min

The Problem in Real Life

Group bookings need a factory like ordinary ones: GroupBooking::create("Daniel Brooks"). Booking already has create(), so Mia just calls it on the child. Daniel's stag party is booked as a plain Booking, with no group size and no group discount.

The parent's factory says return new self($customer);. And in the repository classes, she wants GroupBookingRepository::find() to return ?GroupBooking instead of the interface's ?Booking — but isn't changing a signature exactly what Act 11 said a child must not do?

M

I called create() on GroupBooking. Why did it build a Booking?

Mia

The Class Written vs. the Class Called

self is fixed

self means the class where the code is written. In an inherited factory, that's always the parent.

Narrower returns, wider inputs

A child may promise more (a more specific return type) and accept more (a wider parameter type) — never less.

Substitution

Any code written for the parent must still work with the child. The variance rules guarantee it.

Covariance, Contravariance and Late Static Binding

Changing types safely in children: a child class must be usable wherever its parent is expected. This chapter explains exactly what that allows:

  • Covariance: return types may become more specific.
  • Contravariance: parameter types may become more general.
  • Late static binding: static:: and new static follow the class that was actually called.
  • Other languages: generic variance in Kotlin and C#, and static methods in Java.

The substitution rule: code written for a BookingRepository interface must keep working with any class that implements it — this is the Liskov substitution principle, the "L" in SOLID (Act 22). So an implementation may give the caller more than promised, and may ask for less, but never the other way round. PHP checks these rules on every method that overrides or implements another, and stops with "Declaration of … must be compatible with …" when they're broken.

Covariance: narrower return types: if the interface promises find(int $id): ?Booking, an implementation may promise something more specific: find(int $id): ?GroupBooking. Every GroupBooking is a Booking, so callers expecting a booking still get one. A return type that changes in the same direction as the class hierarchy is called covariant, and PHP allows it since 7.4. The same rule lets mixed become string, a union int|string become int, and a parent's self become the child.

Covariance: a narrower return type is allowed
<?php
declare(strict_types=1);
class Booking {}
class GroupBooking extends Booking {}
interface BookingRepository
{
public function find(int $id): ?Booking;
}
class GroupBookingRepository implements BookingRepository
{
public function find(int $id): ?GroupBooking // promises more: allowed
{
return $id === 7 ? new GroupBooking() : null;
}
}
$repo = new GroupBookingRepository();
echo get_class($repo->find(7)), "\n"; // GroupBooking
var_dump($repo->find(8)); // NULL

Contravariance: wider parameter types: parameters go the other way. If the parent accepts notify(SmsNotifier $n), a child may accept more: notify(Notifier $n), the interface, because any SmsNotifier callers pass is still accepted. That's contravariant. Narrowing a parameter — accepting int where the parent accepted int|string — would break callers that pass a string, so PHP refuses it. Property types are stricter still: a normal property's type can't change at all in a child (invariant), because it's both read and written. (PHP 8.4's property hooks relax this for get-only properties — chapter 7.) The diagram below puts both rules side by side.

What a child may change: return types narrower, parameter types wider

Parent: find(int $id): ?Booking

the promise callers rely on

the child may

Return type → ?GroupBooking

✓ narrower: callers still get a Booking

Parameter → int|string $id

✓ wider: callers' ints still accepted

the child may not

Return type → ?object

✗ wider: callers might not get a Booking

Parameter → only positive int

✗ narrower: some callers' ints refused

Contravariance: wider parameters yes, narrower no
<?php
interface Notifier {}
class SmsNotifier implements Notifier {}
class Reminder
{
public function via(SmsNotifier $n): string { return "sms"; }
}
class FlexibleReminder extends Reminder
{
public function via(Notifier $n): string { return "any"; } // accepts more: allowed
}
class AnyObjectReminder extends Reminder
{
public function via(object $n): string { return "objects"; } // even wider: allowed
}
echo (new FlexibleReminder())->via(new SmsNotifier()), "\n"; // any
// Narrowing would fail when PHP loads the class, e.g. via(int $n) after via(int|string $n):
// Fatal error: Declaration of … must be compatible with …
Narrowing a parameter is refused
<?php
class Booking
{
public function setNote(int|string $note): void {}
}
class GroupBooking extends Booking
{
public function setNote(int $note): void {} // accepts less than the parent
}
// Fatal error: Declaration of GroupBooking::setNote(int $note): void must be compatible
// with Booking::setNote(string|int $note): void

Late static binding: in a static method, self means "the class this code is written in", always. In Booking::create(), new self(...) builds a Booking, even when the call was GroupBooking::create() — Mia's bug. static means "the class that was called", decided at runtime: new static(...) builds a GroupBooking when called on GroupBooking. This is called late static binding (LSB), because the class is bound late, at runtime. The same applies to static::method(), static::CONSTANT and the return type : static, which promises "an instance of whichever class you called me on". Use static in factories and fluent methods that children inherit; use self when you really mean this exact class. The diagram below shows the two answers to "which class?".

GroupBooking::create() — self vs. static

GroupBooking::create("Daniel Brooks")

create() is written in Booking, inherited by GroupBooking

inside create()

new self(...)

self = the class the code is WRITTEN in → Booking

new static(...)

static = the class that was CALLED → GroupBooking

result

A plain Booking: no group discount

the bug

A GroupBooking

the fix

Mia's bug: new self in an inherited factory
<?php
declare(strict_types=1);
class Booking
{
public function __construct(public string $customer) {}
public static function create(string $customer): self
{
return new self($customer); // always Booking, wherever it's called from
}
public static function createLate(string $customer): static
{
return new static($customer); // the class that was called
}
}
class GroupBooking extends Booking {}
echo get_class(GroupBooking::create("Daniel Brooks")), "\n"; // Booking — the bug
echo get_class(GroupBooking::createLate("Daniel Brooks")), "\n"; // GroupBooking
static:: for constants and methods too
<?php
class Booking
{
public const KIND = "single";
public function describe(): string
{
return "self: " . self::KIND . ", static: " . static::KIND;
}
}
class GroupBooking extends Booking
{
public const KIND = "group";
}
echo (new GroupBooking())->describe(), "\n"; // self: single, static: group

Generic variance — not in PHP: variance matters most with generics: is a List<GroupBooking> a List<Booking>? Kotlin (out T, in T), C# (out T, in T) and Scala let you declare the answer per type parameter, and Java uses wildcards (? extends Booking). PHP has no generics (Act 11), so it has no generic variance either; PHPStan's @template-covariant docblocks (Act 21) cover it in analysed code.

Kotlin: declaration-site variance on generics (not in PHP)
// Kotlin — "out T" makes a list of a subtype usable as a list of the supertype
interface Source<out T> {
fun next(): T
}
fun printAll(s: Source<Booking>) { /* ... */ }
val groups: Source<GroupBooking> = TODO()
printAll(groups) // allowed: Source is covariant in T
// PHP has no generics, so no variance on type parameters;
// PHPStan supports /** @template-covariant T */ in docblocks.

Static methods without LSB in Java: here PHP has something Java doesn't. In Java and C#, static methods aren't virtual: there's no equivalent of static:: or new static(), so an inherited static factory can only build the class it names, and Java code uses separate factories or generics instead. PHP's late static binding is what makes patterns like Laravel's Booking::create([...]) on every model possible. The table below sums up the rules.

Table — What a child may change
ElementAllowed changeNameExample
Return typeNarrower (more specific)Covariance?Booking → ?GroupBooking
Parameter typeWider (more general)ContravarianceSmsNotifier → Notifier
Property typeNo changeInvariancestring stays string
VisibilitySame or more visible—protected → public
self in a static factoryAlways the class writtenEarly bindingnew self() builds Booking
static in a static factoryThe class calledLate static bindingnew static() builds GroupBooking

Key Takeaway

A child must be usable wherever its parent is (Liskov substitution). So return types may become narrower (covariance: ?Booking → ?GroupBooking) and parameter types wider (contravariance: SmsNotifier → Notifier); property types stay the same (invariance). In static and inherited code, self is the class written, static is the class called (late static binding): new static() in a factory builds the right child. PHP has no generic variance (Kotlin/C# in and out), and unlike Java and C# it does support late static binding.

Why This Matters

The variance rules are what make interfaces trustworthy: whatever class arrives behind BookingRepository, the caller's code keeps working. Knowing them turns PHP's "must be compatible" errors from a mystery into a two-second fix.

Late static binding is behind every inherited factory and fluent method in modern PHP — Model::create(), Model::query(), $builder->where(...) in Laravel all rely on static. Getting self and static right is the difference between a subclass that works and one that quietly turns into its parent.

create() uses new static, and Daniel's stag party is a GroupBooking again. While cleaning up, Mia looks at an older class, LegacyBooking, which stores its data in a private array and uses magic __get() to read it. A report reads $booking->stauts — a typo — gets null, and treats every booking as pending. No warning at all. That's the next chapter: magic methods for property access.