Re: [RFC][Discussion] Return Type Variance Checking
| From: | Stanislav Malyshev | Date: | Thu, 27 Nov 2014 07:48:29 +0000 |
| Subject: | Re: [RFC][Discussion] Return Type Variance Checking | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-79214@lists.php.net to get a copy of this message | ||
Hi!
>> class FooFactory {
>> function create(Foo $foo): Foo { return $foo; }
>> }
>>
>> class GooFactory extends FooFactory {
>> function create(Goo $goo): Goo { return $goo; }
>> }
> OK HHVM allows it - we also allow it but trigger an E_STRICT error
> @see http://3v4l.org/UhtOb
This is because this code has LSP violation - if you have an object
about which you know it's typed as FooFactory, you should be able to
call it with any Foo object. But if this object is a GooFactory instead,
now not any Foo would serve, but only a subset of them - namely, Goo.
This clearly violates the principle "everything good for the parent must
be good for the child". Since PHP is a kind and nurturing language, we
only produce E_STRICT, some other languages would refuse to accept such
thing or interpret it as two different methods.
See also:
https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Covariant_method_argument_type
--
Stas Malyshev
smalyshev@gmail.com