本文介绍了为什么三元运算符忽略条件顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究三元操作嵌套,并使用此例程进行了一些测试:

I was studying about ternary operation nesting and made some tests with this routine:

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

尽管我知道为什么它没有以我期望的方式打印字符串(它之前忽略了所有内容条件测试),因为它在三元运算符周围没有括号,尽管如此,它仍显示出一些奇怪的行为。

Although I know why it's not printing the string in the way I'd expect (it ignores everything before conditional test) because it lacks parenthesis around the ternary operator, it's showing some curious behavior despite of that. It's inverting the operator's evaluation priority.

按原样编写的此测试应返回 11.25 ,因为 11.25> 10 ,但是它返回不相关的值!

This test, written as it is, should return 11.25 since 11.25 > 10, but instead it returns an irrelevant value!

如果我更改< 用于> 的运算符,然后应打印不相关的值,因为它为 true ,但其结果为 false 并打印 11.25 。

If I change the < operator for >, it should then print an irrelevant value, since it's true, but it evaluates to false and print 11.25 anyway.

有人可以向我解释为什么会发生吗?就像我说过的,我知道,上面的语句在语法上是错误的,但是我愿意理解为什么它改变了PHP的逻辑工作方式。

Can anyone explain to me why it happens? Like I've said, I know the above statement is syntactically wrong, but I'm willing to understand why it alters the way PHP works the logic.

推荐答案

列出了PHP运算符及其优先级。根据此表,

http://php.net/manual/en/language.operators.precedence.php lists the PHP operators with their precedence. According to this 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.')




  • / 的绑定比紧密。

  • 。的绑定比<
  • $ b紧$ b
  • < 的绑定比?:

    • / binds tighter than .
    • . binds tighter than <
    • < binds tighter than ?:
    • 换句话说,您正在比较字符串'首次通过。第二轮将11.25’标记为数字 10 。

      In other words, you're comparing the string 'First passed. The second round marks 11.25' to the number 10.

      这篇关于为什么三元运算符忽略条件顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:51