BeetleJuice
BeetleJuice

Reputation: 40886

Correct phpDoc to tell IDE of dynamic class return type

Consider this code:

class ParentClass {

    /** @return ParentClass  */
    public function getNew(){
        return call_user_func(array($this,'generator'));
    }

    protected function generator(){
        return new static(); // will actually return whatever class calls this code
    }
}

class ChildClass extends ParentClass {}

$child = new ChildClass();
var_dump($child->getnew()); // object(ChildClass)

Because ParentClass::generator() returns a static(), when the child instance calls getNew(), a ChildClass() is returned. The IDE (PhpStorm in my case) has no way to resolve this since the generator is dynamically called with call_user_func(). As a result, the IDE thinks that a ParentClass instance will be returned:

enter image description here

Is there a way to improve the parent's phpDoc block to better reflect the return type?

Upvotes: 0

Views: 1614

Answers (1)

BeetleJuice
BeetleJuice

Reputation: 40886

I figured it out, using this phpDoc block for ParentClass::getNew():

/** @return static */
public function getNew(){/*...*/}

phpDoc Types keywords

self - An object of the class where this type was used, if inherited it will still represent the class where it was originally defined.

static - An object of the class where this value was consumed, if inherited it will represent the child class. (see late static binding in the PHP manual).

$this - This exact object instance, usually used to denote a fluent interface.

PhpStorm 2017.2 understands it, and recognizes that $child->getNew() will return a child instance. The IDE doesn't quite call it ChildClass, but rather static. Still it autocompletes the methods and properties that belong exclusively to the child class.

Upvotes: 4

Related Questions