Re: Proposal: Type Casting User Classes

From: Date: Fri, 15 Nov 2013 11:30:41 +0000
Subject: Re: Proposal: Type Casting User Classes
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-70155@lists.php.net to get a copy of this message
As a thought. Would it not be possible to, instead of implementing a new __cast method, make use of the existing __clone functionality? Effectively aren't you trying to clone one object into another just of another type? While I can't think of many use cases off the top of my head, I certainly see the benefit of this proposal and it doesn't seem to have any BC that I can see. (First post so please excuse me if I'm missing things / making a daft point.) Cheers. Jonny. On Thu, Nov 14, 2013 at 6:39 PM, Chris London <me@chrislondon.co> wrote: > Hey everyone, > > I want to get a feel for something I would like to implement into PHP core. > I would like to be able to cast objects to my own class types. Similar to > already available PHP syntax: > > $foo = (string) $bar; > > The syntax would look like this: > > $foo = (\My\FooObject) $bar; > > It would also support: > > $foo = ( (\My\FooObject) $bar )->myFooObjectFunction(); > > I'm still trying to decide what would happen internally and I would like > some feedback. I'm thinking of 3 different things it could do: > > 1) Directly change the class type, functionally equivalent to: > > function castType($object, $type) { > return unserialize(preg_replace("/^O:[0-9]+:\"[^\"]+\":/i", > "O:".strlen($type).":\"$type\":", serialize($object))); > } > > 2) Throw a fatal error if the object doesn't match the type trying to be > cast. > > 3) Add a new static magic method called __cast() that would allow the > developer to decide what happens. Like this: > > namespace \My; > > class FooObject { > public static function __cast($foo) { > // Do stuff here > return new FooObject; > } > } > > I'm willing to implement this myself if everybody else likes this idea. > Thanks! > > Chris London >

« previous php.internals (#70155) next »