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

From: Date: Wed, 15 Mar 2017 18:13:58 +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-98540@lists.php.net to get a copy of this message
On Wed, Mar 15, 2017 at 11:49 AM, 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? > I like the idea kind of, but would this remove the ability to cast to array all classes not implementing __toArray, as is the case with __toString? This would be a HUGE BC if so: $ php -r 'class Foo {public $foo = "foobar";} var_dump((array) (new Foo));' array(1) { ["foo"]=> string(6) "foobar" } $ php -r 'class Foo {public $foo = "foobar";} var_dump((string) (new Foo));' PHP Recoverable fatal error: Object of class Foo could not be converted to string in Command line code on line 1 $ php -v PHP 7.1.2 (cli) (built: Feb 27 2017 00:02:44) ( ZTS ) > Regards, > > Benoît Burnichon >

« previous php.internals (#98540) next »