1

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?

useless
  • 1,876
  • 17
  • 18
  • I created a bug report for vscode . since it cannot handle Generics properly. https://github.com/bmewburn/vscode-intelephense/issues/2144 unless there is some other way to do it for it. – useless Feb 16 '22 at 22:18
  • unfortunately at the current date a team member of vscode's intelephense has anwer `Generics are not currently supported.` – useless Feb 17 '22 at 15:31

1 Answers1

5

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

useless
  • 1,876
  • 17
  • 18
Nico Haase
  • 11,420
  • 35
  • 43
  • 69
  • in your example the parameter `$a` is also the returned instance. I need parameter to be a string that describes the class returned. foo('stdClass') should be inferred as: foo($c:string):stdClass, and foo('DateTime') as foo($c:string):DateTime – useless Feb 16 '22 at 15:39
  • @useless please see my revised code. This time, I've checked it using PHPStan before answering :P – Nico Haase Feb 16 '22 at 15:54
  • 1
    I had already find that, unfortunately vscode is not recognizing the return type. – useless Feb 16 '22 at 19:54