-
-
Notifications
You must be signed in to change notification settings - Fork 938
Closed
Labels
Description
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
$classNamevariable 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 donew A()explicitly for instance, which is probably a better way to write the code anyway. - Errors go away if the
swicth/caseis replaced with an equivalentif/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!
Reactions are currently unavailable