Re: [PHP-DEV] [RFC] Nullable Casting

  105210
April 10, 2019 15:16 guilliam.xavier@gmail.com (Guilliam Xavier)
On Wed, Apr 10, 2019 at 4:34 PM Mark Randall <markyr@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
  105212
April 10, 2019 15:47 markyr@gmail.com (Mark Randall)
On 10/04/2019 16:16, Guilliam Xavier wrote:
> var_dump((?int) $obj); // would you want it to print `NULL`? > var_dump((?string) $obj); // would you want it to print `NULL`?
I believe returning null in those situations makes the most intuative sense, yes. > var_dump((int) $obj); // Notice, then prints `int(1)` In the absense of a nullable modifier, that makes so little sense that it definitely needs to throw a TypeError IMO. -- Mark Randall