PHP null coalesce + ternary operators strange behavior
I'm facing unexpected behavior when using new PHP7 null coalesce operator with ternary operator.
Concrete situation(dummy code):
function a()
{
$a = 1;
$b = 2;
return $b ?? (false)?$a:$b;
}
var_dump(a());
The result is int(1).
Can anybody explain me why?
Your spaces do not reflect the way php evaluates the expression. Note that the ??
has a higher precedence than the ternary expression.
You get the result of:
($b ?? false) ? $a : $b;
Which is $a
as long as $b
is not null
or evaluates to false
.
Examine the statement return $b ?? (false)?$a:$b;
return $b ?? (false)?$a:$b;
This first evaluates $b ?? (false)
$b ?? (false)
whose result is then passed to ? $a:$b
? $a:$b
;
$b ?? (false)
$b ?? (false)
means give the first not null and isset
value, which in this case is $b
Since $b = 2
, which is a true-ish value, above expression becomes:
return ($b) ? $a : $b
($b) ? $a : $b
which returns value of $a
which is int(1)
This whole thing will make better sense if you think of original return statement as:
return ($b ?? (false)) ? $a : $b;
($b ?? (false)) ? $a : $b;
We dont need to add the additional brackets because ??
is evaluated before ?
上一篇: 是PHP线程