Re: Proposal: AS assertions
| From: | Jordi Boggiano | Date: | Fri, 22 Mar 2024 13:06:20 +0000 |
| Subject: | Re: Proposal: AS assertions | ||
| References: | 1 2 3 4 5 6 7 8 9 10 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-122727@lists.php.net to get a copy of this message | ||
On 2024-03-22 10:46, Rowan Tommins [IMSoP] wrote:
On Fri, 22 Mar 2024, at 08:17, Jordi Boggiano wrote: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.beWe perhaps could make sure that as does not throw if used withWhile 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??, 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