Re: Add __toArray() method to objects that would be called on cast to array

From: Date: Wed, 15 Mar 2017 20:41:15 +0000
Subject: Re: Add __toArray() method to objects that would be called on cast to array
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-98545@lists.php.net to get a copy of this message
This is a BC break due to the fact that the (array) cast is used to extract property information from private properties in library code. On 15 Mar 2017 6:50 p.m., "Benoît Burnichon" <bburnichon@gmail.com> wrote: > 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 >

« previous php.internals (#98545) next »