Re: What about a magic __toArray() method?
| From: | Midori Koçak | Date: | Tue, 04 Feb 2020 07:18:10 +0000 |
| Subject: | Re: What about a magic __toArray() method? | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-108352@lists.php.net to get a copy of this message | ||
Or we can deprecate __toString() method at all and detect cast events
instead. Would it make more sense? Something like this __casted().
P.S: I saw the previous conversation but hence now we have types, it would
make sense.
Midori
On Tue, 4 Feb 2020 at 08:15, Midori Koçak <mtkocak@gmail.com> wrote:
> As you know we have __toString method that runs whenever an object is
> typecasted to string or it is directly echoed.
>
> <?php
>
> $class = (new class{
> public function __toString(){
> echo "casted\n";
> return "mahmut\n";
> }
> });
>
> echo $class;
> $casted = (string)$class;
>
> /*
> prints:
> casted
> mahmut
> casted
> mahmut
> */
>
>
> As you know toArray() method implemented when an object is converted into
> and array and most of the time when a plain data object is sent to
> front-end.
>
> Having a magic method like __toString called __toArray would be useful to
> detect and act on conversion events.
>
> Roughly it would be like:
>
> <?php
>
> $class = (new class{
> public function __toArray(){
> echo "casted\n";
> return
> [
> 'key'=>'value'
> ];
> }
> });
>
>
> $casted = (array)$class;
> print_r($casted);
>
> /*
> prints:
> Array
> (
> [key] => value
> )
> mahmut
> */
>
> What would you think? I think it would add value.
>