Re: Proposal: Type Casting User Classes
| From: | Chris London | Date: | Thu, 14 Nov 2013 21:13:33 +0000 |
| Subject: | Re: Proposal: Type Casting User Classes | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-70130@lists.php.net to get a copy of this message | ||
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.
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 */ )
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.
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