On Mon, Oct 30, 2023, at 11:17 AM, Ilija Tovilo wrote:
> Hi Robert
>
> On Sun, Oct 29, 2023 at 7:31 PM Robert Landers <landers.rob...@gmail.com> 
> wrote:
>>
>> Hello Internals,
>>
>> We currently have a null coercion operator: ??, but we lack an
>> anti-null coercion operator.
>> ...
>> fn() =>
>>   ($_SERVER['HTTP_X_MY_HEADER'] ?? null)
>>   ? md5($_SERVER['HTTP_X_MY_HEADER'])
>>   : null;
>> ...
>> This is rather tedious when you have to do it, so, I'd like to discuss
>> adding a new "anti-null coercion" operator: ?!
>>
>> This would collapse the previous verbose code into:
>>
>> fn() =>
>>   $_SERVER['HTTP_X_MY_HEADER']
>>   ?! md5($_SERVER['HTTP_X_MY_HEADER'];
>
> This does not seem significantly less verbose to me. The main
> motivation for ?? was that it avoids repeating the expression over
> something like ?:. I would see a stronger argument for this feature if
> it offered the same benefit. E.g.
>
> $_SERVER['HTTP_X_MY_HEADER'] ?! md5($$)
>
>> It would have a lower precedence than ?? so that the above line would
>> read from left to right without requiring parenthesis/brackets. The
>> operator would only return the right-hand side if the left-hand side
>> exists (aka, not null), otherwise, it would return null.
>
> I think it should have a higher precedence.
>
> $_SERVER['HTTP_X_MY_HEADER'] ?! md5($$) ?? 'abc'
> ==>
> ($_SERVER['HTTP_X_MY_HEADER'] ?! md5($$)) ?? 'abc'
>
> Otherwise the result is NULL if the header is missing, given that the
> coalesce operator is never executed.
>
> That said, while I've certainly encountered this situation, it's
> nothing a temporary variable can't fix. I don't personally believe
> there's a strong need for such an operator.
>
> Ilija

Another point to note is that for objects, we already have ?->, which 
effectively serves this purpose.  It is sugar for:

is_null($o) ? null : $o->whatever()

So any new operator would only be relevant for free-standing variables (which 
is automatically a code smell) or arrays, and I'm not convinced the latter is a 
large enough use case in a decently written code base.  (You really should know 
what your data is, and the best way to do that is map it into a proper object, 
at which point ?-> comes into play.)

--Larry Garfield

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to