Re: What about a magic __toArray() method?
| From: | Rowan Tommins | Date: | Tue, 04 Feb 2020 11:19:16 +0000 |
| Subject: | Re: What about a magic __toArray() method? | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-108363@lists.php.net to get a copy of this message | ||
On Tue, 4 Feb 2020 at 10:37, Marco Pivetta <ocramius@gmail.com> wrote:
> Correct: an explicit
$foo->toArray() call suffices.
>
> For other readers, more about $foo->toArray() vs
> (array) $foo is
> described at
>
>
> https://github.com/ShittySoft/symfony-live-berlin-2018-doctrine-tutorial/pull/3#issuecomment-460441229
>
The pros and cons of overloading casts are roughly the same as those of
operator overloading in general:
on one hand:
+ It is more succinct than calling a method
+ It aids creation of richer Domain Specific Languages
on the other:
- It is less explicit than choosing a purpose-specific method name
- It is less flexible than having multiple related methods, or a method
with parameters
- It is harder to predict behaviour at a glance
> Or we can deprecate __toString() method at all and detect cast events
> instead. Would it make more sense? Something like this __casted().
If there was a good case made for how it should work, I'd be more
supportive of a general feature to overload casting, rather than making
(array) a special case.
One of many challenges would be working out when the cast should happen
implicitly. Should "iterable $foo" trigger an array cast if the object
isn't iterable? Should foreach()? Should strict_types change that behaviour
as it does for __toString(), even though it currently only applies to
scalar types?
Regards,
--
Rowan Tommins
[IMSoP]