|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2016-05-12 13:50 UTC] mbrowne83 at gmail dot com
Description: ------------ It seems that PHP does not support covariant parameter types. It should be possible to override a base class method and make its parameter type more specific. In the code example, the warning message is erroneous (or at least arbitrary) because the code does in fact conform to the Liskov Substitution Principle and is valid OOP. Test script: --------------- //example use case from https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Covariant_method_return_type class Animal {} class Cat extends Animal {} class AnimalShelter { function putAnimal(Animal $a) {} } class CatShelter extends AnimalShelter { function putAnimal(Cat $c) {} } Expected result: ---------------- No output Actual result: -------------- Warning: Declaration of CatShelter::putAnimal(Cat $c) should be compatible with AnimalShelter::putAnimal(Animal $a) in /vagrant/test.php on line 14 PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Oct 27 16:00:01 2025 UTC |
How much of that Wikipedia entry did you read? 1. As it says, Eiffel is "[unique] among mainstream languages" for its support for covariant parameters. 2. The code does not obey LSP because of exactly what the entry points out: CatShelter needs to support everything that AnimalShelter does. By restricting the parameter to only Cat objects, it *breaks* LSP "which states that objects of subclasses should always be less restricted than objects of their superclass". function PutDogInShelter(AnimalShelter $shelter) { $dog = new Dog(); // class Dog extends Animal $shelter->putAnimal($dog); } The above code needs to work with all AnimalShelter-type objects, however it will not work with CatShelters.