Skip to content

Inconsistency between null safe operator and property fetch with null coalesce #8661

Closed
@rajyan

Description

@rajyan

Description

Noticed this issue while investigating phpstan/phpstan#7291.

The following code:
https://3v4l.org/bgVKX

<?php

echo $a?->foo;
echo $a?->foo ?? '';
echo isset($a?->foo);

echo $a->foo;
echo $a->foo ?? '';
echo isset($a->foo);

Resulted in this output:

Warning: Undefined variable $a in /in/bgVKX on line 3

Warning: Undefined variable $a in /in/bgVKX on line 4

Warning: Undefined variable $a in /in/bgVKX on line 7

Warning: Attempt to read property "foo" on null in /in/bgVKX on line 7

But I expected this output instead:

Warning: Undefined variable $a in /in/bgVKX on line 3

Warning: Undefined variable $a in /in/bgVKX on line 7

Warning: Attempt to read property "foo" on null in /in/bgVKX on line 7

I think line 4 should not report a warning because the undefined var $a is handled by null coalescing operator like in line 8.
I believe it is a bug, because the inconsistency between line 4 and 5 (null coalesce vs isset), line 4 and line 8 (null safe vs non null safe) is hard to expect.

PHP Version

PHP 8.0.1 - 8.1.6

Operating System

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions