Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

phpstorm

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?

like image 421
Matt Gibson Avatar asked Oct 20 '14 16:10

Matt Gibson


1 Answers

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.

like image 120
Matt Gibson Avatar answered Oct 27 '22 11:10

Matt Gibson