Skip to content

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

Closed

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

Activity

  1. damianwadley commented on May 31, 2022

    @damianwadley
    Member

    Agreed that both line 4's $a?->foo ?? '' and line 8's $a->foo ?? '' should behave the same.

  2. cmb69 commented on May 31, 2022

    @cmb69
    Member

    Agreed that both line 4's $a?->foo ?? '' and line 8's $a->foo ?? '' should behave the same.

    I tend to agree, but maybe @iluuu1994 can clarify.

  3. iluuu1994 commented on May 31, 2022

    @iluuu1994
    Member

    I agree. JMP_NULL currently always calls ZVAL_UNDEFINED_OP1(), even if compiled through zend_compile_coalesce(). It would make sense to avoid the undefined variable error here. This requires passing the BP type in the JMP_NULL opcode through extended_value. As extensions might depend on that value, I'm not sure if it makes more sense to only patch for PHP 8.2.

  4. self-assigned this
    on Jun 1, 2022
  5. added a commit that references this issue on Jun 12, 2022
    5a855ee
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions