Re: Type casting syntax
| From: | Larry Garfield | Date: | Mon, 12 Jul 2021 15:00:45 +0000 |
| Subject: | Re: Type casting syntax | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-115410@lists.php.net to get a copy of this message | ||
On Mon, Jul 12, 2021, at 9:26 AM, Levi Morrison via internals wrote:
> > What are the use cases for integrated object to object (ie, class to class) conversion in
> > PHP? Rust's type system is a very different beast, so its casting logic makes more sense
> > there. I'm not entirely clear on what the use case is in PHP. When would that be superior to
> > "just write an asFoo() method and move on with life"?
> >
> > Scalar conversion I can see, but every time someone suggests adding siblings to
> > __toString(), there's major pushback.
> >
> > --Larry Garfield
> >
> > --
> > PHP Internals - PHP Runtime Development Mailing List
> > To unsubscribe, visit: https://www.php.net/unsub.php
> >
>
> The features I was referring to are not casting; casting does exist in
> Rust but this is not it. Rather, it's a generic way to convert
> objects. It's nice to have a standard way to do it, instead of every
> project doing something bespoke. It also can enable some use cases
> that aren't relevant in PHP (yet) such as taking any generic type
> which can be converted into a T, because you only want to do that
> transformation conditionally on something else.
So, like David suggested, some standardized version of $foo->as($type), which then returns an
instance of $type?
I... don't think I've ever done that often enough to justify a standard feature for it.
When have you run into it?
That also seems quite different from what Max is talking about:
On Mon, Jul 12, 2021, at 9:54 AM, Max Semenik wrote:
> I was thinking of something akin to many compiled languages' approach of
> "consider this expression is now of that type, and throw an exception if
> it's not". An example of this approach from Benjamin's proposal of old^
>
> $service = (EmailService) $diContainer->get('email.service');
>
> Instead of
>
> /** @var EmailService $service */
> $service = $diContainer->get('email.service');
> if (!$service instanceof EmailService) {
> throw new TypeError('Expected instance of EmailService, ...');
> }
Hm, that's a different creature. I... would be probably OK with something in that direction,
though I wouldn't work on it myself. I think what you're describing here is more of a
type assertion. "Assert that this variable is of type X, otherwise bail." So, some kind
of non-disableable (or maybe disableable?) shorthand for
assert($foo instanceof Bar).
--Larry Garfield