Re: RFC: Not Null Assertion Operator
| From: | MrMeshok | Date: | Fri, 07 Feb 2025 09:21:36 +0000 |
| Subject: | Re: RFC: Not Null Assertion Operator | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-126325@lists.php.net to get a copy of this message | ||
>
> Examples of potentially using in PHP:
> Without this operator we writing this code:
>
> $foo = ...
>
> if ($foo === null) {
> throw new FooIsNullException();
> }
>
> $foo->bar.
>
> With this operator:
>
> $foo!->bar
> $foo!->someProperty->method();
> $foo!->someProperty->anotherProperty!->method();
I see where you're coming from, in my code I had to deal with a lot of
APIs with models which have nullable properties, but they shouldn't be
null if some conditions are met.
So I work with them in this way
```php
if ($response->code === ResponseCode::Success) {
// order and quantity are nullable
return $response->data->order->quantity ?? throw new
UnexpectedResponseException($response);
// With method calls you would need to add nullsafe operators
// order and date are nullable
return $response->data->order?->date?->format('Y-m-d') ?? throw
new UnexpectedResponseException($response);
}
```
UnexpectedResponseException is just an exception that keeps faulty
response, so I can catch it and act on it, or it just gets logged and
I can show producers of API that they have a problem.
I see a point in !-> operator if it would work just like that. Throws
a specific error that has an object that triggered this error.