Re: Union type casts
| From: | Marco Pivetta | Date: | Wed, 05 Oct 2022 18:01:19 +0000 |
| Subject: | Re: Union type casts | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-118758@lists.php.net to get a copy of this message | ||
On Wed, 5 Oct 2022 at 19:53, Eugene Sidelnyk <zsidelnik@gmail.com> wrote:
> I used to have an awkward feeling when it was necessary to convert the
> nullable integer into a nullable string. It would be kind of ternary
> operator anyway. Either
$b = (null !== $a) ? (string)$a : null;
> or `$b =
> (string)$a ?: null;`.
>
> A lot easier to read would it be if written this way: $b =
> (?string)$a;.
> The intentions are clear when doing explicit type-cast.
>
> Currently, I don't see any other situations when this feature may be useful
>
I don't think that this tiny edge case warrants a new language feature.
I can endorse using [azjezz/psl](
https://github.com/azjezz/psl/blob/34391b78f097e7d489bd618d2cb15ef474937896/src/Psl/Type/TypeInterface.php#L21-L26)
for this though:
```php
use Psl\Type;
$myValue = Type\union(Type\int(), Type\null())
->coerce($input);
```
This will also throw an exception (**GOOD**) if the cast is not safe to
perform.
Marco Pivetta
https://twitter.com/Ocramius
https://ocramius.github.io/