Re: What about a magic __toArray() method?

From: Date: Tue, 04 Feb 2020 10:35:29 +0000
Subject: Re: What about a magic __toArray() method?
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-108360@lists.php.net to get a copy of this message
Marco, I've read it and your argument is strong. I think my opinion slightly moves towards Andreas, away from magic. here is something I wrote some days ago: https://github.com/midorikocak/arraytools/blob/master/src/ArrayConvertableTrait.php I guess you were saying something like this would be enough. Midori On Tue, 4 Feb 2020 at 11:31, Marco Pivetta <ocramius@gmail.com> wrote: > Hey Midori, > > This has been discussed in more depth 2 years ago: > https://externals.io/message/98539#98539 > > In practice, the (array) cast is one of the few operations that > don't > cause observable side-effects in this programming language: let's please > keep it as such. > > Marco Pivetta > > http://twitter.com/Ocramius > > http://ocramius.github.com/ > > > On Tue, Feb 4, 2020 at 8:15 AM 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. >> >

« previous php.internals (#108360) next »