Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 739
useless Avatar asked Aug 07 '26 18:08

useless


1 Answers

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

like image 97
Nico Haase Avatar answered Aug 09 '26 09:08

Nico Haase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!