Skip to content

SimpleXMLElement + null safe operator results in errors #6020

@PHLAK

Description

@PHLAK

Bug report

When using the null safe operator with SimpleXMLElement phpstan reports an error. More specifically, phpstan doesn't seem to understand that the properties of a SimpleXMLElement object can possibly return null.

Using nullsafe property access on non-nullable type SimpleXMLElement. Use -> instead.

Code snippet that reproduces the problem

https://phpstan.org/r/68f49c78-6d49-4e4c-96f0-83562eff662e

Here's some additional code illustrating the way properties on the SimpleXMLElement object work.

>>> $foo = new SimpleXMLElement('<foo>asdf</foo>')
=> SimpleXMLElement {#5830
     +"0": "asdf",
   }
>>> $foo
=> SimpleXMLElement {#5830
     +"0": "asdf",
   }
>>> $foo->bar
=> SimpleXMLElement {#5839}
>>> $foo->bar->baz
=> null
>>> $foo->bar->baz->qux
<warning>PHP Warning:  Attempt to read property "qux" on null in eval()'d code on line 1</warning>
=> null

This is a bit odd because $foo->bar (a non-existent element in the XML) returns an empty SimpleXMLElement. Perhaps I'm missunderstanding the way the SimpleXMLElement object works.

Expected output

No errors

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions