Reputation:
I'm using PHP 7.2.0
I've understood the normal basic usage of null coalescing operator(??) but I'm not able to understand the execution flow and functionality of when null coalescing operator(??) is nested.
Please consider below code example and explain me the execution-flow in step-by-step manner.
<?php
$foo = null;
$bar = null;
$baz = 1;
$qux = 2;
echo $foo ?? $bar ?? $baz ?? $qux; // outputs 1
?>
Upvotes: 2
Views: 2012
Reputation: 662
You could translate the null coalescing operator in a series of if/elseif/else statements. From you example:
echo $foo ?? $bar ?? $baz ?? $qux; // outputs 1
Translated into if/else statements:
<?php
$foo = null;
$bar = null;
$baz = 1;
$qux = 2;
if (isset($foo)) {
echo $foo;
}
else if (isset($bar)) {
echo $bar;
}
else if (isset($baz)) {
echo $baz;
}
else {
echo $qux;
}
Personaly I use the null coalescing operator very sparingly and nesting it seems like a recipe for disaster.
The null coalescing operator (apart from having a really annoying name), does not improve the readability of your code. I don't think the few lines spared is worth the extra mental overhead it requires when reading your code. Or is worth having other people having trouble reading/comprehend your code. So be a nice programmer to your fellow programmers and use the null coalescing operator sparingly and never nest it.
Upvotes: 1
Reputation:
It works in similar manner as it works in its basic usage.
The execution flow will be as follows :
isset($foo)
it's not been set, it contains NULL
so, go for $bar
isset($bar)
it's not been set, it's too contains NULL
so, go for $baz
isset($baz)
it's been set, it contains the value 1
so, it gets printed and execution stops.Upvotes: 1
Reputation: 15629
I think your example becomes cleaner, if you add parens around the single steps of the null coalescing operator.
echo ($foo ?? ($bar ?? ($baz ?? $qux)));
Basically it's the same as executing from left to right.
The null coalescing operator is right associative. That means that operations are grouped from right to left. I.e, the expression a ?? b ?? c
is evaluated as a ?? (b ?? c)
.
Upvotes: 7