Re: Proposal: AS assertions
| From: | Rowan Tommins [IMSoP] | Date: | Tue, 19 Mar 2024 19:38:42 +0000 |
| Subject: | Re: Proposal: AS assertions | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-122695@lists.php.net to get a copy of this message | ||
On 19/03/2024 16:24, Robert Landers wrote:
$x = $attributeReflection->newInstance() as ?MyAttribute; if ($x === null) // do something since the attribute isn't MyAttributeI think reusing nullability for this would be a mistake - ideally, the right-hand side should allow any type, so "$foo as ?Foo" should mean the same as "$foo as Foo|null". A better alternative might be to specify a default when the type didn't match: $x = $attributeReflection->newInstance() as ?MyAttribute else null; if ($x === null) // do something since the attribute isn't MyAttribute Which then also allows you to skip the if statement completely: $x = $attributeReflection->newInstance() as MyAttribute else MyAttribute::createDefault(); That then looks a lot like a limited-use version of syntax for catching an exception inline, which would be nice as a general feature (but I think maybe hard to implement?) $x = somethingThatThrows() catch $someDefaultValue; As well pattern matching, which Ilija mentioned, another adjacent feature is a richer set of casting operators. Currently, we can assert that something is an int; or we can force it to be an int; but we can't easily say "make this an int if safe, but throw otherwise" or "make this an int if safe, but substitute null/$someValue otherwise". I've been considering how we can improve that for a while, but not settled on a firm proposal - there's a lot of different versions we *could* support, so choosing a minimal set is hard. Regards, -- Rowan Tommins [IMSoP]