Skip to content

PHPStan incorrectly reports unhandled match cases when using ::class or get_class on a polymorphic variable #12882

@manofearth

Description

@manofearth

Bug report

When using a match expression with $object::class or get_class where $object is typed as a base class, PHPStan incorrectly reports an unhandled match error even when all potential concrete subclasses are handled.

A minimal reproduction case is attached:

  • The error for $object::class is: "Match expression does not handle remaining value: class-string&literal-string"
  • For get_class($object) error is similar: "Match expression does not handle remaining value: class-string"

This occurs even though:

  1. The base class is abstract and cannot be instantiated directly
  2. All concrete child classes are handled in the match expression
  3. Adding the base class to the match arms does not resolve the error. Since the base class is abstract, it should not need to be included in the match cases at all.

My main concern is that I want PHPStan to help me maintain exhaustive matching - when new subclasses of the base class are added, I want PHPStan to warn me that I need to add a new match case. If I add a default branch, I lose this very useful exhaustiveness checking capability.

Code snippet that reproduces the problem

https://phpstan.org/r/8145653a-4c66-4066-86da-27df01b10dfc

Expected output

No errors!

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

I use PHPStan in all my new projects. It helps me write fewer tests and sometimes finds bugs in my code, so yes, I'm happy that it exists.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions