Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch/case with class instantiation from variable can result in unexpected errors #6370

Closed
kevinquinnyo opened this issue Jan 14, 2022 · 2 comments
Labels

Comments

@kevinquinnyo
Copy link

Bug report

Sorry for the bad title. This one is hard for me to explain, but the snippet should help clear it up.

Object instantiation from a class name stored in a variable within a switch/case statement produces an error under the following conditions:

  • if there exists some kind of validation code (or any code) above the switch/case that allows phpstan to determine/guess what the $className variable contains.
  • one of the possible class names in the switch/case requires constructor arguments and the other does not.

You can reproduce this using level 1.

The errors presented are:

  • Class B does not have a constructor and must be instantiated without any parameters.
  • Class A constructor invoked with 0 parameters, 1 required.

Some additional observations:

  • Errors go away if instead of doing new $className... we do new A() explicitly for instance, which is probably a better way to write the code anyway.
  • Errors go away if the swicth/case is replaced with an equivalent if/else.
  • This is admittedly a strange factory pattern, and probably an edge-case that isn't encountered very often, so I assume this is not a high priority bug at first glance.

Code snippet that reproduces the problem

https://phpstan.org/r/bf1178c0-5ca0-4a52-a4c4-93b126344900

Expected output

I expected that phpstan would assume $className could be something like A|B and infer from the case statements which one it must be at the time it's initialized.

Did PHPStan help you today? Did it make you happy in any way?

yes!

@phpstan-bot
Copy link
Contributor

@kevinquinnyo After the latest commit in dev-master, PHPStan now reports different result with your code snippet:

@@ @@
-30: Class B does not have a constructor and must be instantiated without any parameters.
-32: Class A constructor invoked with 0 parameters, 1 required.
+No errors

@github-actions
Copy link

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 16, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

3 participants