3

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?

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

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

3 Comments

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 please see my revised code. This time, I've checked it using PHPStan before answering :P
I had already find that, unfortunately vscode is not recognizing the return type.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.