Skip to content

Instanceof between *NEVER* and XXX will always evaluate to false #3632

@jacekkarczmarczyk

Description

@jacekkarczmarczyk

Bug report

phpstan 0.12.33

Code below throws the Instanceof between *NEVER* and OtherClass will always evaluate to false. error

Code snippet that reproduces the problem

https://phpstan.org/r/27ab1228-4e19-423a-a440-ed26982ac171

<?php declare(strict_types = 1);

trait Foo {
	public function test(): string {
		if ($this instanceof HelloWorld) {
			return 'hello world';
		}
		if ($this instanceof OtherClass) {
			return 'other class';
		}
		throw new \Error();
	}
}

class HelloWorld
{
	use Foo;
	
	function bar(): string {
		return $this->test();
	}
}

class OtherClass {
	use Foo;

	function bar(): string {
		return $this->test();
	}
}

Expected output

No error

Additional notes

Trying to ignore the error with // @phpstan-ignore-line in line 8 behaves differently in my real project where classes and trait are defined in separate files. In playground it supresses the error, but in my project I'm getting the "No error to ignore is reported on line ..." error, probably related to #3464. I can prepare a github repro with reproduction if you want

<?php

// TraitX.php

namespace Foo;

trait TraitX
{
    public function getFromTrait(): bool
    {
        if ($this instanceof ClassA) {
            return false;
        } elseif ($this instanceof ClassB) { // @phpstan-ignore-line
            return true;
        } else {
            throw new \Error();
        }
    }
}
<?php

// ClassA.php

namespace Foo;

class ClassA
{
    use TraitX;

    public function getFoo(): bool
    {
        return $this->getFromTrait();
    }
}
<?php

// ClassB.php

namespace Foo;

class ClassB
{
    use TraitX;

    public function getFoo(): bool
    {
        return $this->getFromTrait();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions