ChatGPT解决这个技术问题 Extra ChatGPT

PHP 7 interfaces, return type hinting and self

UPDATE: PHP 7.4 now does support covariance and contravariance which addresses the major issue raised in this question.

I have run into something of an issue with using return type hinting in PHP 7. My understanding is that hinting : self means that you intend for an implementing class to return itself. Therefore I used : self in my interfaces to indicate that, but when I tried to actually implement the interface I got compatibility errors.

The following is a simple demonstration of the issue I've run into:

interface iFoo
{
    public function bar (string $baz) : self;
}

class Foo implements iFoo
{

    public function bar (string $baz) : self
    {
        echo $baz . PHP_EOL;
        return $this;
    }
}

(new Foo ()) -> bar ("Fred") 
    -> bar ("Wilma") 
    -> bar ("Barney") 
    -> bar ("Betty");

The expected output was:

Fred Wilma Barney Betty

What I actually get is:

PHP Fatal error: Declaration of Foo::bar(int $baz): Foo must be compatible with iFoo::bar(int $baz): iFoo in test.php on line 7

The thing is Foo is an implementation of iFoo, so as far as I can tell the implementation should be perfectly compatible with the given interface. I could presumably fix this issue by changing either the interface or the implementing class (or both) to return hint the interface by name instead of using self, but my understanding is that semantically self means "return the instance of the class you just called the method on". Therefore changing it to the interface would mean in theory that I could return any instance of something that implements the interface when my intent is for the invoked instance is what will be returned.

Is this an oversight in PHP or is this a deliberate design decision? If it's the former is there any chance of seeing it fixed in PHP 7.1? If not then what is the correct way of return hinting that your interface expects you to return the instance you just called the method on for chaining?

I think it's an error in PHP return type-hinting, perhaps you should raise it as a bug; but any fix is unlikely to get into PHP 7.1 at this late stage
Since the last beta version of 7.1 has gone online a few days ago, it's very unlikely that any fix would get into 7.1.
Out of interest, where are you reading your interpretation of how the self return type is supposed to work?
@Adam: It just seems like it's logical for self to mean "Return the instance you called this on, and not some other instance that implements the same interface". I seem to remember Java had a similar return type (though it's been a while since I did any Java programming)
Hi Gordon. Well unless it's documented to work somewhere, I wouldn't count on what might be logical being reality. TBH with the situation I'd describe, I'd just be as declarative as possible and use iFoo as the return type. Is there a situation in which that won't actually work? (I realise this is "advice" / opinion rather than "an answer", that said.

h
hanshenrik

editorial note: the answer below is outdated. as php PHP7.4.0, the following is perfectly legal:

<?php
Interface I{
    public static function init(?string $url): self;
}
class C implements I{
    public static function init(?string $url): self{
        return new self();
    }
}
$o = C::init("foo");
var_dump($o);

3v4l: https://3v4l.org/VYbGn

original answer:

self does not refer to the instance, it refers to the current class. There is no way for an interface to specify that the same instance must be returned - using self in the manner you're attempting would only enforce that the returned instance be of the same class.

That said, return type declarations in PHP must be invariant while what you're attempting is covariant.

Your use of self is equivalent to:

interface iFoo
{
    public function bar (string $baz) : iFoo;
}

class Foo implements iFoo
{

    public function bar (string $baz) : Foo  {...}
}

which is not allowed.

The Return Type Declarations RFC has this to say:

The enforcement of the declared return type during inheritance is invariant; this means that when a sub-type overrides a parent method then the return type of the child must exactly match the parent and may not be omitted. If the parent does not declare a return type then the child is allowed to declare one. ... This RFC originally proposed covariant return types but was changed to invariant because of a few issues. It is possible to add covariant return types at some point in the future.

For the time being at least the best you can do is:

interface iFoo
{
    public function bar (string $baz) : iFoo;
}

class Foo implements iFoo
{

    public function bar (string $baz) : iFoo  {...}
}

That said, I would have expected a return type-hint of static to work, but it isn't even recognised
Paul, deleting the comments you've deleted here is actually harmful because (A) it loses important information, and (B) it disrupts the flow of discussion relative to the other comments. I can't see any reason why your comments relying to Mark and Gordon needed to be deleted. In fact, you're doing this all over the place, and it needs to stop. There is absolutely no good reason to go back to a year-old question and remove all of your comments, completely destroying the flow of discussion. In fact, it's harmful and disruptive.
There is an important preface to a part of your quote seen here: "Covariant return types are considered to be type sound and are used in many other languages (C++ and Java but not C# I believe). This RFC originally proposed covariant return types but was changed to invariant because of a few issues.". I'm curious what issues PHP had. Their design choice causes several limitations that also cause odd issues with traits, rendering them somewhat useless in many cases unless you loosen return type restrictions (as seen in some answers below). Very frustrating.
@MarkBaker the return type static is being added to PHP 8.
Maybe to be the "best" option it also deserves /** @return Foo */ (if you cannot upgrade your PHP version). At least, that way the IDE would be suggesting the right typehint. Tested it with Netbeans.
G
Gabor

It also can be a solution, that you don't define explicitly the return type in the Interface, only in the PHPDoc and then you can define the certain return type in the implementations:

interface iFoo
{
    public function bar (string $baz);
}

class Foo implements iFoo
{
    public function bar (string $baz) : Foo  {...}
}

Or instead of Foo just use self.
A
Alexandru

PHP 8 will add "static return type" which will solve your problem.

Check out this RFC: https://wiki.php.net/rfc/static_return_type


M
Moshe Katz

This looks like the expected behavior to me.

Just change your Foo::bar method to return iFoo instead of self and be done with it.

Explanation:

self as used in the interface means "an object of type iFoo."
self as used in the implementation means "an object of type Foo."

Therefore, the return types in the interface and the implementation are clearly not the same.

One of the comments mentions Java and whether you would have this issue. The answer is yes, you would have the same issue if Java allowed you to write code like that -- which it doesn't. Since Java requires you to use the name of the type instead of PHP's self shortcut, you are never going to actually see this. (See here for a discussion of a similar issue in Java.)


So is declaring self, similar to declaring MyClass::class?
@Laser Yes, it is.
But if Foo implements iFoo then Foo is by definition of type iFoo