Skip to content

Instanceof check sometimes infer wrong result when falsy  #12107

@VincentLanglet

Description

@VincentLanglet

Bug report

In the following example https://phpstan.org/r/568c5370-1a34-42eb-85f5-3ee19e441ed2

$e1 is inferred as Throwable~LogicException but this is not true because I can call the method with $e2 being

  • a class extending LogicException for sayHello
  • a class-string of a class extending LogicException for sayHello2

Code snippet that reproduces the problem

https://phpstan.org/r/568c5370-1a34-42eb-85f5-3ee19e441ed2

Expected output

In this special case, the type should stay Throwable.

But with code like

public function sayHello(Throwable $e1): void
	{
	    $e2 = new LogicException();
		if ($e1 instanceof $e2) {
			return;
		}

		\PHPStan\dumpType($e1);
	}

or

public function sayHello(Throwable $e1): void
	{
	    $e2 = LogicException::class;
		if ($e1 instanceof $e2) {
			return;
		}

		\PHPStan\dumpType($e1);
	}

The inferred result as Throwable~LogicException.
I dunno then if it can be easily fixed... I assume we need something to know

  • if the class (or class-string) is exactly the provided class
  • or if the class (or class-string) is only an instanceof of the provided class

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

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions