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

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

Reply via email to