Since PHP 7.0 brought forward the Null Coalescing Operator (??), writing
more succinct code for how to handle null values has been a blessing. But,
what about the inverse when you want to do something when a value is not
null? You're left with the traditional (and sometimes verbose) methods of
using if conditions or the full-blown ternary operator `$foo !== null ?
<something> : null;`.

I am here to gauge the interest of the community in having an
anti-coalescing operator that would execute code only if the condition is
not null, otherwise returning null in its stead. If this is not a wholly
terrible idea, I will -- as suggested -- then continue to create an
official RFC.

My initial thought process would be to use a similar syntax to the Null
Coalescing Operator (??), but to add negation: `$bar = $foo !??
$foo->getBar()`. I didn't want to use `!?` because then if anybody wanted
to add an anti-ternary operator (e.g., `!?:`) for falsey comparison, then
they'd have to get creative or use the three-character approach I am
already proposing. The purpose is simply to negate the existing behavior,
so at first glance I do not see any BC breakages or additional complexities
that haven't already been addressed - naturally, I could be wrong.

The driving use case, as hinted at in my above example, is if I have a
nullable object I only want to call a method on it if the object is not
null. Otherwise, default to the null value.

I am working through the RFC Howto [https://wiki.php.net/rfc/howto], and it
suggests that I ask for wiki karma for my account (897syudjhf) so that I
may create the RFC when appropriate.

Additionally, I have not [yet] found any existing precedence for
anti-coalescing; i.e., there does not seem to be an elegant counterpart to
COALESCE() in SQL. And, as they say, naming is hard. If
`anti-coalescing-operator` does not sit well with you all, I am open to
naming suggestions.

Thank you for your time,
Ken Stanley

Reply via email to