空合并运算符有一个与 PHP 中的大多数其他比较器不同的先例:
示例 1:
(错误)
$var['x'] = "5";
if ((int)$var['x']??0 < 1 ) {
print "less than 1"; /* outputs this */
}
else {
print "more than 1";
}
这将导致“ less
”,因为比较似乎是在$var['x']
vs之间0<1
,但这肯定会是,但$var['x']??(false)
在我看来,这仍然不能保证这if
是真的。
示例 2:
(错误)
$var['x'] = "5";
if ($var['x']??5 < 1 ) {
print "less than 1"; /* still outputs this */
}
else {
print "more than 1";
}
我确实理解预期的输出;但我不明白PHP 为达到其选择的结论所采取的步骤。
我已经阅读了https://www.php.net/manual/en/language.operators.precedence.php和PHP 短三元(“Elvis”)运算符与空合并运算符,但这些并没有明确概述我认为示例 1 和示例 2 中出现意外行为的原因。
哪些逻辑处理步骤导致其以这种方式工作?
示例 3:
( 正确的 )
$var['x'] = "5";
if ((int)($var['x']??0) < 1 ) {
print "less than 1";
}
else {
print "more than 1";
}
这将产生正确的“ more
”输出。