Skip to content

Instantly share code, notes, and snippets.

@Nex-Otaku
Created February 18, 2021 08:33
Show Gist options
  • Save Nex-Otaku/f8b7189cc96d5aeba47a9a9b65e0e861 to your computer and use it in GitHub Desktop.
Save Nex-Otaku/f8b7189cc96d5aeba47a9a9b65e0e861 to your computer and use it in GitHub Desktop.
Covariance in PHP
<?php
// Covariance - narrowing type on return. Works from PHP 7.4.0 and above
// https://www.php.net/manual/ru/language.oop5.variance.php
class Animal
{
public function getName(): string
{
return 'Some animal';
}
};
class Dog extends Animal
{
public function getName(): string
{
return 'Bucky';
}
};
class House
{
public function getPet(): Animal
{
return new Animal();
}
}
class DogHouse extends House
{
public function getPet(): Dog
{
return new Dog();
}
}
$house = new House();
echo "House pet: {$house->getPet()->getName()}\n";
$dogHouse = new DogHouse();
echo "Doghouse pet: {$dogHouse->getPet()->getName()}\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment