Proposal: Type Casting User Classes
| From: | Chris London | Date: | Thu, 14 Nov 2013 18:39:48 +0000 |
| Subject: | Proposal: Type Casting User Classes | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-70119@lists.php.net to get a copy of this message | ||
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