Re: Functorial interfaces

From: Date: Thu, 12 May 2016 17:02:13 +0000
Subject: Re: Functorial interfaces
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-93284@lists.php.net to get a copy of this message
On 12/05/2016 17:47, Andreas Heigl wrote:
It's the other way around. The interface creates a contract that ensures that you can use ALL methods available in your SpecialClass.
I don't think that's what the interface in the example means: interface Foo {
    public function foo(SpecialClass $object);
} What this says is "an object adhering to interface Foo has a method foo which accepts any SpecialClass instance". In other words, it says that the following is bound to succeed: if ( $thing instanceOf Foo ) {
    $thing->foo( new SpecialClass );
} Marco is right that a class with a wider definition fulfils this contract: class Bar implements Foo {
    public function foo(BaseClass $object)
    {
        // do something with BaseClass $object
    }
} $thing = new Bar; if ( $thing instanceOf Foo ) {
    $thing->foo( new SpecialClass );
} This is called "contravariance of parameters", and has come up a couple of times on the list. In particular, when return types were added, it was discussed that they should technically be covariant (subtypes can "narrow" return types, and say they only return a specific sub-type of the original contract). So from a design point of view, there is no reason not to support it; unfortunately, there are some technical hurdles to implementing that within the PHP engine. Here is a nice summary from Anthony Ferrara: http://marc.info/?l=php-internals&m=142791636808421&w=2 Regards, -- Rowan Collins [IMSoP]

« previous php.internals (#93284) next »