Ala*_*ado 1 php ternary-operator
我正在研究三元操作嵌套,并用这个例程做了一些测试:
<?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]);
Run Code Online (Sandbox Code Playgroud)
虽然我知道为什么它没有以我期望的方式打印字符串(它在条件测试之前忽略了所有内容),因为它缺少三元运算符周围的括号,尽管如此,它仍然显示出一些奇怪的行为.它颠覆了运营商的评估优先级.
这个测试按原样编写,应该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.'
Run Code Online (Sandbox Code Playgroud)
解析为
(('First passed. The second round marks ' . ($test2[1] / $test2[0])) < 10)
? 'an irrelevant value'
: (($test2[1] / $test2[0]) . ' and the third was skipped.')
Run Code Online (Sandbox Code Playgroud)
/ 绑定比紧 .. 绑定比紧 << 绑定比紧 ?:换句话说,您将字符串'First passed. The second round marks 11.25'与数字进行比较10.