三元运营商(猫王运营商)?:
我只是想知道为什么这个代码返回1
$complete = 'complete';
$completed = ($complete == 'complete') ?: 'Not Complete';
而如果我尝试这一个
$complete = 'complete';
$completed = ($complete == 'complete') ? $complete : 'Not Complete';
和这个
$complete = 'complete';
if ($complete == 'complete') {
$completed = $complete;
} else {
$completed = 'Not Complete';
}
他们都返回'complete'
基于这个?:运算符('Elvis运算符')在PHP中
他们都不应该返回相同的价值吗?
这是因为您在第一个示例中进行了布尔检查:
$complete == 'complete' // returns 'true'
操作员告诉,如果陈述是真实的,则返回陈述的值,否则返回“不完整”。 所以它确实如此。 并且true
值表示为1
。
你的例子解释了:
// sets '$completed' to '($complete == 'complete')' what is 'true'
$completed = ($complete == 'complete') ?: 'Not Complete';
// sets '$completed' to '$completed', what is 'NULL', because '$completed' seems to be undefined before
$completed = ($complete == 'complete') ? $completed : 'Not Complete';
// sets '$completed' to the value of '$complete', because the statement is 'true'
if ($complete == 'complete') {
$completed = $complete;
} else {
$completed = 'Not Complete';
}
你可以这样使用Elvis Operator:
$completed = $complete ?: 'Not Complete';
在你的代码中你有这样一个声明:
$completed = true ?: 'Not Complete';
因此它返回true。
链接地址: http://www.djcxy.com/p/57735.html上一篇: Ternary Operator(Elvis Operator) ?:
下一篇: JavaScript "or"