Re: Union type casts
| From: | Stephen Reay | Date: | Wed, 05 Oct 2022 06:34:43 +0000 |
| Subject: | Re: Union type casts | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-118747@lists.php.net to get a copy of this message | ||
> On 5 Oct 2022, at 12:41, Dusk <dusk@woofle.net> wrote:
>
> On Oct 4, 2022, at 21:46, Eugene Sidelnyk <zsidelnik@gmail.com> wrote:
>> $foo = (int|float)$bar;
>
> As written, I wouldn't know what to expect this to do with a string value -- would it cast
> it to int or float?
>
> Based on the behavior of your second example, the answer appears to be "float", so
> this syntax seems to be equivalent to:
>
> $foo = \is_int($bar) ? $bar : (float) $bar;
>
> Or, even more concisely:
>
> $foo = 0+$bar;
>
> I'd be even less sure what to expect when casting to other union types. What would the
> expected result of casting a string to (bool|array|object) be, for example? I'm not sure there
> are many meaningful operations which could be constructed here.
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
Hi,
I think the intention is that it would follow precisely the same casting rules as function
parameters do.
So e.g:
```
function foo(int|float $var) {
return $var;
}
$f1 = foo(‘1’);
$c1 = (int|float) ‘1’;
$f2 = foo(‘1.1’);
$c2 = (int|float) ‘1.1’;
```
In both scenarios the $f1/$c1 and $f2/$c2 would result in the same type.
Your first example isn’t quite the same though; Passing ‘1’ to a parameter typed as
int|float will cast it to an integer, your example casts such a value to a float.
The 0+$value thing is interesting, but also definitely seems less intuitive to my eye.
Given your last comment I think its worth reiterating Eugene’s point is simply about exposing the
**existing** cast behaviour that happens with typed parameters, to be usable on variables.
I can see some benefit in the proposal, but I think I’d be more interested in the ability to
define local variables as being a given type (or union), and then have the engine cast (or error)
when assigning to them - essentially how typed object properties work, but for regular variables.