Re: Proposal: Type Casting User Classes

From: Date: Fri, 15 Nov 2013 01:37:06 +0000
Subject: Re: Proposal: Type Casting User Classes
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-70146@lists.php.net to get a copy of this message
On Nov 14, 2013, at 4:13 PM, Chris London <me@chrislondon.co> wrote: > On Thu, Nov 14, 2013 at 12:20 PM, Pierre du Plessis > <pierre@pcservice.co.za>wrote: > >> >> Do you have any use cases why this would be useful? >> > > Basically the reason I want it is to make sure the function I just called > returned the object I expected. Kind of like how we can specify what object > we're expecting for parameters like this: > > function foo (User $user) { > // do stuff here > } > > I want to be able to make sure the object I have is the right type. In this > case, I wouldn't want it to actually change the object type but instead > through an exception I could catch. (obviously, there are ways to do that > now by writing my own functions and throwing my own exceptions). The > company I'm working for right now uses Zend Framework 2 and in Zend > Framework 2 they have factories which could return just about anything and > I want to make sure I got the right object. I’m confused - on one hand, you’re referring to the already existing type hinting of parameters. On the other, you’re making the case for instanceof. if ($someZendObject instanceof What\I\Expect) This really isn’t a use case for object type casting. > > Another minor use case would be that the IDE would be able to do > function/parameter hints. (I do know some IDEs will let you do /* @var > $foo User */ ) If you’re using a relatively modern IDE and using parameter type hinting, this already exists. > > Another situation we ran across is we're using Propel and we would pull > database records that Propel turns into User objects. If some of those > users are admins then we would want them to be AdminUser objects. Obviously > you could write work arounds like : > > $admin = AdminUser::createFromUser($user); > > or > > $admin = new AdminUser($user); > > but if AdminUser extends User I could see how type casting could be > appropriate. There are two types of object type casts: upcast and downcast. Upcast is when you have a class that refers to an object that inherits from a root class. Downcast is casting an object from the root towards a child or subclass. What you’re referring to is downcasting. (User -> AdminUser). This is the only valid use case provided thus far, but even then, there are other methodological approaches that can be taken to mitigate this scenario. > > 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? >> > > I imagine throwing an exception would be appropriate > > Thanks! > Chris London

« previous php.internals (#70146) next »