Creating instance of Son in Parent's method and having autocomplete.

Are there a way to create an instance of Son class by calling its inherited metho? That generic method shall be inherited from its Parent. The instance shall autocomplete and be treated as Son instance, not Parent.

1. Without creating a "proxy"-function in Son with correct phpdoc @return TheSon.  //**1**
2. Without need to locally specify the variable class or upcasting.  //**2**

There will be many classes inherited from Parent and it would be unelegant to upcast everytime when the new class NewSon is created.

Maybe it can be fixed with phpdoc which allows statements? Like return instance of $self class?

(I assume there are no big difference whether it is an instance's method or static function.)

class TheParent {
     * @return TheParent
    function parentsFunctionToGetInstanceBySomeSearchCriteria($name) {
        $p = new TheParent();
        return $p;

class TheSon extends TheParent {
    function sonsFunction() {

    /** "proxy" fix
     * @param $name
     * @return TheSon
    function sonFixed_parentsFunctionToGetInstanceBySomeSearchCriteria($name) { //**1**
        return $this->parentsFunctionToGetInstanceBySomeSearchCriteria($name);

    $name = 'Mickey';
    $sons = new TheSon();
    $son = $sons->parentsFunctionToGetInstanceBySomeSearchCriteria($name2);

     * The problem: sonsFunction() will not be autocompleted, as this instance is thought to be TheParent.
     * Though it is completely valid to call in my situation.
    $son->sonsFunction();//warning, function not found

     * @var $son TheSon
    $son->sonsFunction();//ok, autocompleted! //**2**

    $son2 = $sons->sonFixed_parentsFunctionToGetInstanceBySomeSearchCriteria($name);
    $son2->sonsFunction();//ok, autocompleted!
1 comment
Comment actions Permalink

Hi Alex,

In theory you should use @return static (or even @return $this should be fine). The problem -- it still does not work as it should in current version of PhpStorm:

Therefore, the "corret" solution (IMO) at the moment is to use inline PHPDoc comment (your #2).


Please sign in to leave a comment.