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.
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?
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::andnew staticfollow 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.
<?phpdeclare(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"; // GroupBookingvar_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
Return type → ?GroupBooking
✓ narrower: callers still get a Booking
Parameter → int|string $id
✓ wider: callers' ints still accepted
Return type → ?object
✗ wider: callers might not get a Booking
Parameter → only positive int
✗ narrower: some callers' ints refused
<?phpinterface 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 …
<?phpclass 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
new self(...)
self = the class the code is WRITTEN in → Booking
new static(...)
static = the class that was CALLED → GroupBooking
A plain Booking: no group discount
the bug
A GroupBooking
the fix
<?phpdeclare(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 bugecho get_class(GroupBooking::createLate("Daniel Brooks")), "\n"; // GroupBooking
<?phpclass 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 — "out T" makes a list of a subtype usable as a list of the supertypeinterface 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.
| Element | Allowed change | Name | Example |
|---|---|---|---|
| Return type | Narrower (more specific) | Covariance | ?Booking → ?GroupBooking |
| Parameter type | Wider (more general) | Contravariance | SmsNotifier → Notifier |
| Property type | No change | Invariance | string stays string |
| Visibility | Same or more visible | — | protected → public |
| self in a static factory | Always the class written | Early binding | new self() builds Booking |
| static in a static factory | The class called | Late static binding | new 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.
