Re: [RFC - discussion] __toArray()
| From: | Steven Wade | Date: | Tue, 04 Feb 2020 16:04:08 +0000 |
| Subject: | Re: [RFC - discussion] __toArray() | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-108394@lists.php.net to get a copy of this message | ||
> Sorry if it's been said in the discussion so far, but I do not see why
>
print_r should convert anything to an array. It accepts
> multiple
> kinds of types including strings, numbers, and so on, and I think
> adding this behavior to print_r is a different thing than
> wanting a
> standard way for objects to be converted into arrays.
You’re right, that’s my bad. I swore I tested print_r() with a class and __toString() and it
cast it, but I just ran it again and it just outputs the object. The goal would be to have
__toArray() behave on arrays like __toString() does on strings. I’ll update the RFC to remove the
reference to print_r(). Thanks!
> And on that note, what is the motivation for wanting a magic method
> for converting an object into an array? Why not make it an explicit
> operation? I do not see the point of the magic here, except _maybe_
> for adding it to ArrayObject or something to allow it to work
> with
> the array_* functions that work without references, in which case I
> think we think this RFC is the wrong approach as it is inadequate for
> that purpose.
PHP’s pretty magical already, so adding another magic method isn’t out of the question and would
keep things inline with how some things are done already. The idea for having magical casting is to
make it simpler in the user land for general array behavior when reading or looping.