Covariance & Contravariance in PHP

Return Type Covariance

Covariance allows a child’s method to return a more specific type than the return type of its parent’s method.

interface AnimalShelter
{
    public function adopt(string $name): Animal;
}

class CatShelter implements AnimalShelter
{
// instead of returning class type Animal, it can return class type
    public function adopt(string $name): Cat 
 Cat
    {
        return new Cat($name);
    }
}

class DogShelter implements AnimalShelter
{
// instead of returning class type Animal, it can return class type Dog
    public function adopt(string $name): Dog 
    {
        return new Dog($name);
    }
}

$kitty = (new CatShelter)->adopt("Ricky");
$kitty->speak();
echo "\n";

$doggy = (new DogShelter)->adopt("Mavrick");
$doggy->speak();

// output
// Ricky meows
// Mavrick barks

Parameter Type Contravariance

Contravariance allows a parameter type to be less specific in a child method, than that of its parent.

class Food {}

class AnimalFood extends Food {}

abstract class Animal
{
    protected string $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function eat(AnimalFood $food)
    {
        echo $this->name . " eats " . get_class($food);
    }
}

<?php

class Dog extends Animal
{
    public function eat(Food $food) {
        echo $this->name . " eats " . get_class($food);
    }
}

$kitty = (new CatShelter)->adopt("Ricky");
$catFood = new AnimalFood();
$kitty->eat($catFood);
echo "\n";

$doggy = (new DogShelter)->adopt("Mavrick");
$banana = new Food();
$doggy->eat($banana);

// output
// Ricky eats AnimalFood
// Mavrick eats Food

source: https://www.php.net/manual/en/language.oop5.variance.php

«
»

Leave a Reply

Your email address will not be published. Required fields are marked *