Created
February 18, 2021 08:33
-
-
Save Nex-Otaku/f8b7189cc96d5aeba47a9a9b65e0e861 to your computer and use it in GitHub Desktop.
Covariance in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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