On Wed, Apr 10, 2019 at 4:34 PM Mark Randall <mar...@gmail.com> wrote:
>
> (Continuing from my previous post in a different thread...)
>
> IMHO a cast such as ([?]type) would be better described as passing a
> mixed value through a function which has a return type of whatever is in
> the cast... the mechanics of that function determine what is returned,
> so long as it conforms to the cast type.
>
> A cast should always either return a value that would be accepted by a
> function argument of an identical type to the cast, or it should throw
> an exception.
>
> function x(T $value) { ... }
> x(T) - Always OK
> x((T)$var) - Always OK
> x($var) - Function may throw a TypeError if it cannot be converted in a
> very strict manner.
>
> To my mind, (?int) is quite explicit, in that it returns an integer or
> null, and it is quite logical to expect it to return null in lieu of
> throwing a TypeError if a conversion is not possible. Naturally,
> (?int)null would return null.
>
> I see a lot of potential use in (?int)$value ?? $default.
>
> Equally I see a lot of use in the following to nullify unexpected inputs
> such as if $_GET['something'] was an array:
>
> $input = (?string)$_GET['input'] ?? '';

So, for example:

```php
$obj = (object) ["foo" => 42];


(function (int $x) { var_dump($x); })($obj); // TypeError
(function (?int $x) { var_dump($x); })($obj); // TypeError

var_dump((function ($x): int { return $x; })($obj)); // TypeError
var_dump((function ($x): ?int { return $x; })($obj)); // TypeError

var_dump((int) $obj); // Notice, then prints `int(1)`
var_dump((?int) $obj); // would you want it to print `NULL`?


(function (string $x) { var_dump($x); })($obj); // TypeError
(function (?string $x) { var_dump($x); })($obj); // TypeError

var_dump((function ($x): string { return $x; })($obj)); // TypeError
var_dump((function ($x): ?string { return $x; })($obj)); // TypeError

var_dump((string) $obj); // Recoverable fatal error
var_dump((?string) $obj); // would you want it to print `NULL`?
```

I have no clear answer myself (other than the current proposal)...

-- 
Guilliam Xavier

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to