Re: Proposal: Type Casting User Classes
| From: | Pierre du Plessis | Date: | Thu, 14 Nov 2013 19:20:57 +0000 |
| Subject: | Re: Proposal: Type Casting User Classes | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-70120@lists.php.net to get a copy of this message | ||
On Thu, Nov 14, 2013 at 8: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
>
Hi
Do you have any use cases why this would be useful?
IMO an object is only meant to do what it is created for.
Converting objects to different types can have very unexpected results.
If you want to reuse code, you can just use traits, or you can use
dependency injection to get functionality of one object inside another.
Also what would happen if you cast objects to invalid types?
E.G if you convert a person entity to a product entity, which doesn't have
the same properties or methods?