Skip to content

False positive: Assignment in if statement causes "Calling method on possibly null value" #647

@iluuu1994

Description

@iluuu1994

Here's a small demo:

https://phpstan.org/r/747de7f4958a04636ecfb3e0b56a47c5

class Foo
{
	/**
	 * @return $this|null
	 */
    public function foo()
    {
        if (rand(0,1) === 1) {
            return $this;
        } else {
            return null;
        }
    }
}

$foo = new Foo();

if (null !== $bar = $foo->foo()) {
    $bar->foo();
}

21 Calling method foo() on possibly null value of type Foo|null.

As you can see, $bar should be of type Foo but PHPStan for some reason thinks that the value may be null. Interestingly, this error message goes away as soon as you remove the doctype.

Is this a known issue?

I've just started using PHPStan yesterday and it's awesome! 🤘 Thank you so much for your hard work!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions