phpvisual-studio-codephpstanpsalm-php

defining generic return for a method/function in php with phpdocblock


Is there a way to specify that a function will return an object of a specific type, where the type is the string of one of the parameters?

e.g.

/**
 * @return object<$class>
 */
public function create(string $class): object {
 ... some factory stuff
}

so that vscode or phpstorm will know that when I do

$myvar = X::create('MyClass');

$myvar will be of type MyClass and I'll have the proper intellisense/autocompletion for it?


Solution

  • This could work using templates like this:

    /**
     * @template T of object
     * @psalm-param class-string<T> $a
     * @param class-string<T> $a
     * @return T
     */
    function foo($a)
    {
        return $a;
    }
    

    But I don't know whether VSCode already supports that. PhpStorm for example doesn't know how to handle the returned value properly