为什么三元运算符忽略条件顺序


Why is ternary operator ignoring condition order?

我正在学习三元运算嵌套,并使用这个例程做了一些测试:

<?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

谁能给我解释一下为什么会这样?就像我说过的,我知道上面的语句在语法上是错误的,但是我愿意理解为什么它改变了PHP的工作逻辑方式。

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进行比较。