On 2024-03-22 10:46, Rowan Tommins [IMSoP] wrote:
On Fri, 22 Mar 2024, at 08:17, Jordi Boggiano wrote:
We perhaps could make sure that as does not throw if used with `??`, or that `??` catches the type error and returns the right-hand expression instead:

So to do a nullable typecast you would do:

    $a as int|float ?? null


While this limits the impact to only expressions combining as with ?? it still has the same fundamental problem: you can't meaningfully use it with a nullable type.


As a concrete example, imagine you have an optional $description parameter, and want to ensure any non-null values are converted to string, but keep null unchanged.

At first sight, it looks like you could write this:

$descString = $description as string|null ?? (string)$description;

But this won't work - the ?? swallows the null and turns it into an empty string, which isn't what you wanted. You need some syntax that catches the TypeError, but preserves the null:

$descString = $description as string|null else (string)$description;
// or
$descString = $description as string|null catch (string)$description;
// or
$descString = $description as string|null default (string)$description;


I actually think there are quite a lot of scenarios where that idiom would be useful:

$optionalExpiryDateTime = $expiry as ?DateTimeInterface else new DateTimeImmutable($expiry);
$optionalUnixTimestamp = $time as ?int else strotime((string)$time);
$optionalUnicodeName = $name as ?UnicodeString else new UnicodeString( $name );
etc

Yeah I think this looks great actually, minus the confusing bits about |null which is in reality yes probably rarely useful in a "as" cast.

as that throws + default to catch it👍🏻

Best,
Jordi

--
Jordi Boggiano
@seldaek -https://seld.be

Reply via email to