Skip to content

Reporting call on X|null using php8 null safe operator #4527

@michalhosna

Description

@michalhosna

Bug report

In php8, the new null safe operator ?-> was added. When using it in combination with ?? for calling method/accesing properties on values of array like this:

($array['key'] ?? null)?->bar

phpstan incorrectly reports

Cannot access property $bar on T|null.

even though we are using the null safe operator, and the code behaves as expected (return nulls, when the key in the array does not exist).

Code snippet that reproduces the problem

https://phpstan.org/r/d831442b-e70b-48eb-b8ac-d68332590815

<?php declare(strict_types = 1);

class Foo
{
	public function foo(): void
	{
		/** @var Bar[] */
		$array = [];
		
		$value = ($array['randomKey'] ?? null)?->bar;
	}
}

class Bar {
	public mixed $bar;
}

Expected output

To not report any errors

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