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

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]);

虽然我知道为什么它没有按照我期望的方式打印字符串(它忽略条件测试之前的所有内容)因为它缺少三元运算符周围的括号,尽管如此它还是显示出一些奇怪的行为。它正在反转运算符的评估优先级。

例子

这个测试,照原样写,应该 return 11.25 因为 11.25 > 10,而是 returns an irrelevant value!

如果我为 > 更改 < 运算符,它应该打印 an irrelevant value,因为它是 true,但它的计算结果为 false 并且无论如何打印 11.25

任何人都可以向我解释为什么会这样吗?正如我所说,我 知道 上面的语句在语法上是错误的,但我愿意理解为什么它会改变 PHP 逻辑的工作方式。

http://php.net/manual/en/language.operators.precedence.php 列出了 PHP 运算符及其优先级。根据这个table,

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