Re: Add __toArray() method to objects that would be called on cast to array
| From: | Andrey Andreev | Date: | Wed, 15 Mar 2017 18:39:00 +0000 |
| Subject: | Re: Add __toArray() method to objects that would be called on cast to array | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-98542@lists.php.net to get a copy of this message | ||
Hi,
On Wed, Mar 15, 2017 at 8:31 PM, Benoît Burnichon <bburnichon@gmail.com> wrote:
>> 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 )
>>
>
> No. For me, classes not implementing __toArray() should keep current
> behavior. That was what I had in mind when I wrote that __toArray() should
> have a default standard implementation.
>
> Same restrictions could be applied to this magic method:
>
> http://us3.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring
>
> By this, I mean, no exceptions should be thrown in this method and return
> value MUST be an array.
Exceptions cannot be thrown from inside __toString() because that's
hard to implement; it's not a "feature" that anybody wanted.
Cheers,
Andrey.