我正在学习三元运算嵌套,并使用这个例程做了一些测试:
<?php
$test1 = [15,30,'ok'];
$test2 = [8,90,'fail'];
$test3 = [4,32,'ok'];
$test1[2] == 'ok' ?
print('First passed. The second round marks '.
$test2[1]/$test2[0] < 10 ? 'an irrelevant value' : $test2[1]/$test2[0].
' and the third was skipped.') :
print('First failed. The second round was skipped and the third marks '.
$test3[1]/$test3[0] < 10 ? 'an irrelevant value' : $test3[1]/$test3[0]);
虽然我知道为什么它没有按照我期望的方式打印字符串(它忽略了条件测试之前的所有内容),因为它在三元操作符周围缺少括号,尽管如此,它还是显示了一些奇怪的行为。它颠倒了运算符的求值优先级。
例子这个测试,按原样编写,应该返回11.25
,因为11.25 > 10
,但它返回an irrelevant value
!
如果我改变>
的<
操作符,它应该打印an irrelevant value
,因为它是true
,但它的计算结果是false
,并打印11.25
。
http://php.net/manual/en/language.operators.precedence.php列出了PHP操作符的优先级。根据这个表格
'First passed. The second round marks ' . $test2[1] / $test2[0] < 10
? 'an irrelevant value'
: $test2[1] / $test2[0] . ' and the third was skipped.'
解析为
(('First passed. The second round marks ' . ($test2[1] / $test2[0])) < 10)
? 'an irrelevant value'
: (($test2[1] / $test2[0]) . ' and the third was skipped.')
-
/
比.
结合更紧密 -
.
比<
结合更紧密 -
<
比?:
结合更紧密
换句话说,您正在将字符串'First passed. The second round marks 11.25'
与数字10
进行比较。