Add __toArray() method to objects that would be called on cast to array
| From: | Benoît Burnichon | Date: | Wed, 15 Mar 2017 17:49:40 +0000 |
| Subject: | Add __toArray() method to objects that would be called on cast to array | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-98539@lists.php.net to get a copy of this message | ||
Hi all,
Looking at code of PHPUnit, I stumbled upon an inconsistent array
conversion:
------
/**
* @param ArrayAccess|array $other
*/
function evaluate($other)
{
// type cast $other as an array to allow
//support in standard array functions.
if ($other instanceof ArrayAccess) {
$data = (array) $data;
}
$patched = array_replace_recursive($other, $this->subset);
// ...
}
-----
This would work only for
ArrayAccess implementations extending
ArrayObject as shown by https://3v4l.org/ti4aY
Looking at the manual
http://php.net/manual/en/language.types.array.php#language.types.array.casting
,
it seems ArrayObject class does not comply to array casting because
integer public properties could also be retrieved. Some tests showed that
regular class always have string keys even when a `$key = 0; $this->{$key}
= 'avalue'; is called. In this case, var_export((array)$object);` returns
array('0' => 'avalue') (Notice the quote around key 0 -
https://3v4l.org/6QW70)
What do you think of adding an optional __toArray() method to classes
which would default to current behavior but would allow specifying
behavior. The way of internal __toString() method and could explain
inconsistency of the ArrayObject class?
Regards,
Benoît Burnichon