Re: Proposal: Type Casting User Classes
| From: | Matthew Leverton | Date: | Fri, 15 Nov 2013 14:29:38 +0000 |
| Subject: | Re: Proposal: Type Casting User Classes | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-70156@lists.php.net to get a copy of this message | ||
On Thu, Nov 14, 2013 at 12: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;
>
I've thought about this feature before in the context of PHP because I
do think it would be useful, but I'm not sure if there's really a way
to implement it that is any better than userland solutions. Your
proposed __cast() call means that every object needs to know about
every object which breaks down when multiple projects are involved.
(Sure, it solves some cases nicely.)
And I wouldn't be a fan of implicit conversions like:
function foo (Foo $foo) { }
foo(new Bar());
Assuming Bar does not descend from Foo, I wouldn't want a cast to Foo
to be implicitly performed even if Bar had an appropriate "cast"
method.
So ultimately, I don't really see how a PHP solution is any better
than just using home made explicit casts:
$bar = cast_foo_to_bar($foo);
or
$bar = $foo->castToBar();
So I think the idea has merit, but I don't know that there's a good
way to implement it.
--
Matthew Leverton