Matt Gibson Matt Gibson - 7 months ago 84
PHP Question

In PHPStorm, how can I make type hinting work when I have a superclass method that returns a different type from each subclass

I have a class that is inheriting from a superclass and where the superclass has a static

find()
method that instantiates instances of the subclass (active record pattern).

class ActiveRecordClass {

/**
* @return mixed
*/
public static function find() {
// Code returns instance of called class
}
}

class ModelClass extends ActiveRecordClass {

}

// returns instance of ModelClass, but PHPStorm doesn't realise
ModelClass::find($model_id);


At the moment, the docblock is not much good for code completion and type hinting. I can't use the superclass as a return type as the subclasses have different methods due to DB columns.

How can I indicate to PHPStorm that the superclass
find()
method returns an instance of the subclass it's called from, so that code completion works?

Answer

Found it:

class ActiveRecordClass {

    /**
     * @return static
     */
    public static function find() {
        // Code returns instance of called class
    }
}

It seems that @return self vs @return static works the same way that you would expect given what the keywords normally do. @return self did not pick up the methods available on the concrete subclass, but @return static make autocomplete work great.