Advertisement
Advanced PHP, Type Declarations & Strict Types

How does PHP's type variance, specifically covariance and contravariance, affect how return types and parameter types can be safely changed when overriding a method in a child class?

Short answer

When a child class overrides a method inherited from a parent class, PHP allows the child's overridden method to declare a more specific return type than the parent's declared return type, a concept known as covariance, since returning a more specific type still fully satisfies…

Save PHP mock interview
Advertisement
AModel answer
When a child class overrides a method inherited from a parent class, PHP allows the child's overridden method to declare a more specific return type than the parent's declared return type, a concept known as covariance, since returning a more specific type still fully satisfies anyone expecting the original, more general parent type, while for parameter types, PHP allows the reverse, called contravariance, meaning a child class's overridden method may accept a more general parameter type than the parent originally declared, since it can still correctly handle every value the more specific parent type would have accepted, and understanding this distinction helps avoid confusing type declaration errors when designing class hierarchies.
class Animal {}
class Dog extends Animal {}

class AnimalShelter {
    public function adopt(): Animal { return new Animal(); }
}

class DogShelter extends AnimalShelter {
    public function adopt(): Dog { return new Dog(); } // Covariant return type, allowed
}
Real-world example
A DogShelter class overrides its parent AnimalShelter's adopt method to specifically return a Dog rather than a generic Animal, which PHP allows because a Dog is still always a valid Animal, satisfying every expectation of anyone calling the original parent method.
Likely follow-ups
  • What would happen if a child class tried to declare a more general return type than its parent instead?
  • How common is it in practice to actually need to understand variance rules when writing typical application code?
Related topics