On Sun, Oct 29, 2023 at 8:53 PM Sergii Shymko <ser...@shymko.net> wrote:
>
>
>
> On Oct 29, 2023, at 1: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.
>
> For example, if I wanted to operate on a header, if-and-only-if it
> exists, I'd have to write something like this one-liner:
>
> fn() =>
>  ($_SERVER['HTTP_X_MY_HEADER'] ?? null)
>  ? md5($_SERVER['HTTP_X_MY_HEADER'])
>  : null;
>
> Or something like this:
>
> function() {
>  if(!empty($_SERVER['HTTP_X_MY_HEADER']) {
>    return md5($_SERVER['HTTP_X_MY_HEADER']);
>  }
>
>  return 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'];
>
> When it is null, it will stay null, thus the above is the same as:
>
> fn() =>
>  $_SERVER['HTTP_X_MY_HEADER']
>  ?! md5($_SERVER['HTTP_X_MY_HEADER']
>  ?? null;
>
> 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'm not particularly attached to the ?! syntax (since it does, in
> fact, look very similar to ?:), so perhaps focusing on the merits of
> the idea first, then bikeshedding the syntax later would be a good
> approach?
>
> Thoughts?
>
> Robert Landers
> Software Engineer
> Utrecht NL
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>
> Hi Robert,
>
> Why don’t you combine the two examples and use a regular ternary operator 
> along with isset/empty()?
>
> fn() =>
>   !empty($_SERVER[‘HTTP_X_MY_HEADER’])
>   ? md5($_SERVER[‘HTTP_X_MY_HEADER’])
>   : null;
>
> It’s only ever so slightly longer than the proposed ?! operator, but way more 
> powerful. You explicitly control the evaluation expression along with the 
> default value.
>
> Regards,
> Sergii

Hey Sergii,

> Why don’t you combine the two examples and use a regular ternary operator 
> along with isset/empty()?

Because falsy is different than null/non-existent. The closest
equivalent is "array_key_exists" (instead of empty/isset) but this
proposal isn't just applicable to arrays. I run into this pattern of
"if not null, then do something with the value" pretty often and it is
tedious to type it out.

Robert Landers
Software Engineer
Utrecht NL

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

Reply via email to