0

Is it possible for PhpStorm to understand the outcome of a method with specified parameters or when called from a specific class to know the outcome if it's defined in the PHPDoc?

For example:

class demo {
    public static function getInstance($className)
    {
        return $className::Instance();
    }
}
class someClass {
    public function Instance() {
        return new someClass();
    }
}

class otherClass {
    public function Instance() {
        return new otherClass();
    }
}

demo::getInstance('someClass'); // PHPstorm should understand this would return someClass
demo::getInstance('otherClass'); // PHPstorm should understand this would return otherClass

At the moment my PhpStorm says

Method getInstance not found in string.

For code hinting I'd like PhpStorm to understand what sort of class is returned based on the parameter value. It would be fine to put that data in the PHPDoc or anything like that, just not additional methods please.

1
  • 1
    If you need to return method type based on passed parameter (some sort of factory/container) -- look at Advanced Metadata -- that's how Laravel IDE Helper works (for example) Commented May 24, 2017 at 13:59

1 Answer 1

2

First, you call non-static methods statically.

Second, you can note return type, like this:

/**
 * @return someClass|otherClass
 */
public static function getInstance($className)
{
    return $className::Instance();
}
Sign up to request clarification or add additional context in comments.

3 Comments

I know it should be static, it's just an example. It's correct in my real code. If I set the return type like that it could also produce code hints from other classes instead of the class that is actually returned.
Whilst not explicitly stated, I think the question may be asking if there's a way of PhpStorm knowing what type of class it is returning, without having to have all of the possibilities listed in the @return statement, so if I had a class Foo, which had the function Instance(), could demo::getInstance('Foo'); be known to PhpStorm without Foo being declared as a return type?
@gabe3886, no. PhpStorm can only propose all variants. PhpStorm generate auto phpdoc like my answer (enumerate all possible return types).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.