[php-src] Issue #7740: Access behavior of SimpleXMLElement changes when element has sibling

From: Date: Thu, 09 Dec 2021 12:38:04 +0000
Subject: [php-src] Issue #7740: Access behavior of SimpleXMLElement changes when element has sibling
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-238302@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/7740
Comment Author: LeonMelis

This behavior is not only observed when being dumped or inspected via xdebug. It is actually exposed
via get_object_vars, and probably some other methods as well.

> Is there a particular issue in code you're encountering because of this, or is it just
> that the output is surprising (and arguably inaccurate)?

Yes, we discovered this behavior due to unexpected result in production code.
We have code that verifies the structure of an XML file like this:

```php
foreach (get_object_vars($simpleXMLElement) as $key => $val) {
    // do validation of $key and $value
}
```

Here, $key could suddenly become '0' instead of 'baz', depending on
whether the **parent** XMLElement contains more than 1 item (a sibling, so to say).

Reading your comment, it looks like we can do a workaround by always accessing an
SimpleXMLElement instance as an array with one item, so with
$simpleXMLElement[0], like this:


```php
// Note: we must always treat SimpleXMLElement as an array, because
// sometimes PHP treats the object as an array internally. By accessing
// it as an array we *should* get consistent behavior.
// See: https://github.com/php/php-src/issues/7740
foreach (get_object_vars($simpleXMLElement[0]) as $key => $val) {
    // do validation of $key and $value
}
```

But that feels like a hack. And as you can see, this would require adding comment lines to explain
to anyone trying to maintain this code why this construct is needed. I cannot blame someone from
being confused by this, as it is unexpected and (as far as I can tell) undocumented behavior.

I understand that this is an edge-case, and changing this behavior might actually break existing
implementations. Maybe the solution should be to clarify this somewhere in the documentation, and
just live with it.


Thread (1 message)

  • noreply@php.net
« previous php.bugs (#238302) next »