Skip to content

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

@kevinquinnyo

Description

@kevinquinnyo

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions