compiler icon indicating copy to clipboard operation
compiler copied to clipboard

Not-Null pipe operator

Open thekid opened this issue 3 months ago • 3 comments

Proposal

Complement the null-coalescing operator:

$user= $context->userName() ?? 'guest';

Sometimes we want to perform an action if the value is null, and perform an alternative instead:

$user= $context->userName();
return null === $user ? null : strtoupper($user);

We already have a "standard" for chaining expressions with the pipe operator. The above without null handling would be:

return $context->userName() |> stroupper(...);

👉 To accomplish this, this feature request suggests a null-safe pipe operator, which would make the following an equivalent of the above:

return $context->userName() ?|> strtoupper(...);

Consistency

This is consistent with the null-safe object operator. If we rewrote the above using a String class, we could have the following:

return $context->userName()?->toUpper();

However, wrapping every primitive string in a String instance would introduce quite a bit of runtime and development overhead!

See also

  • https://stackoverflow.com/questions/62929428/opposite-of-nullish-coalescing-operator
  • https://wiki.php.net/rfc/pipe-operator
  • https://wiki.php.net/rfc/pipe-operator-v2
  • https://github.com/php/php-src/pull/7214
  • https://docs.hhvm.com/hack/expressions-and-operators/pipe
  • https://github.com/tc39/proposal-pipeline-operator
  • https://github.com/tc39/proposal-pipeline-operator/issues/159 - brings up ?>
  • https://github.com/tc39/proposal-pipeline-operator/issues/210 - more pipeline operators, includes ?|>
  • https://elixirschool.com/en/lessons/basics/pipe_operator
  • https://gleam.run/cheatsheets/gleam-for-php-users/#piping
  • https://externals.io/message/107661 - anti-coalescing via !??
  • https://externals.io/message/107661#107670 - ?|> suggested

thekid avatar Mar 26 '24 11:03 thekid