Skip to content

Null check is forgotten when using null coalescing or ternary #12677

@stefanfisk

Description

@stefanfisk

Bug report

When storing a null check as a variable the original variables nullness is forgotten if it is checked again by other means.

Here's an example that will dump Foo|null.

<?php declare(strict_types = 1);

class Foo {
	public function getBool():bool
	{
		return true;
	}
}

function test1(?Foo $foo) {
	$hasFoo = $foo !== null;

	$bool = $foo?->getBool() ?? false;

	if ($hasFoo) {
		\PHPStan\dumpType($foo);
	}
}

Reusing the null check variable works as expected;

function test3(?Foo $foo) {
	$hasFoo = $foo !== null;

	$bool = $hasFoo ? $foo->getBool() : false;

	if ($hasFoo) {
		\PHPStan\dumpType($foo);
	}
}

Code snippet that reproduces the problem

https://phpstan.org/r/23293d2b-6f7f-4704-8994-0a4e223e862d

Expected output

I'd expect the null check to not be forgotten.

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
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions