phpstan: Access to undefined property with `??` operator

Summary of a problem or a feature request

When using the ?? operator, phpstan can report accesses to undefined properties

Code snippet that reproduces the problem

https://phpstan.org/r/1c68ba92dc8e52d8aa8fcc5e24904efa

Expected output

PHPStan should probably not report anything here. For comparison, this does not cause anything to be reported.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 15 (15 by maintainers)

Most upvoted comments

Don’t think this should be implemented: yes, the ?? operator is quite lax, but dynamic properties are an edge case compared to messing up a property name in a class with declared properties.

And yes: this goes against the language semantics, but given the rarity of dynamic property access in comparison with access to undefined properties (when using ?? and isset()), this would likely be a step back for most applications.

A pattern on how to code isset($dynamicObject->dynamicProperty['somethingSomething']) without arguing too much with the type checker would be much better.

EDIT: to simplify this comment, implementing this “fix” would lead to following code being acceptable under PHPStan constraints, which is NOT OK:

class A {
    private $property;
    public function get()
    {
        return $this->proeprty ?? 'foo'; // notice the typo
    }
}

https://phpstan.org/r/1c68ba92dc8e52d8aa8fcc5e24904efa

Interesting aspects. This helps to get around with. Thanks for your ideas. 👍