Skip to content

Match expression on get_class or ::class should infer like instanceof checks #5371

@Jasonoro

Description

@Jasonoro

Feature request

Currently, PHPStan support using isinstance checks to find out whether or not a class might be a superclass, and infers that correctly. For example, the following code produces no errors:

class A {
	public function methodA(): int {
		return 1;
	}
}

class B extends A {
	public function methodB(): int {
		return 2;
	}
}

function getSomeClass(): A {
	return new B();
}

$somePossibleSuperclass = getSomeClass();
$number = null;
if ($somePossibleSuperclass instanceof B) {
	$number = $somePossibleSuperclass->methodB();
}
else if ($somePossibleSuperclass instanceof A) {
	$number = $somePossibleSuperclass->methodA();
}
//PHPStan sees `number` as an int here.

However, when using the match expression with get_class or ::class, it does not work correctly:

class A {
	public function methodA(): int {
		return 1;
	}
}

class B extends A {
	public function methodB(): int {
		return 2;
	}
}

function getSomeClass(): A {
	return new B();
}

$somePossibleSuperclass = getSomeClass();
$number = match($somePossibleSuperclass::class) {
	B::class => $somePossibleSuperclass->methodB(),
	A::class => $somePossibleSuperclass->methodA()
};
------ -------------------------------------------------------------------
  Line   test.php                                                          
 ------ -------------------------------------------------------------------
  20     Match expression does not handle remaining value: class-string<A>
  21     Call to an undefined method A::methodB().
 ------ -------------------------------------------------------------------

It would be great if this kind of inference would work correctly, as it is a very nice pattern to use.

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

PHPStan saved me a couple of times, and the generics support is amazing :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions