【问题标题】:How following script is evaluated?如何评估以下脚本?
【发布时间】:2014-09-25 11:05:53
【问题描述】:
<?php echo true?'what':true?'will':'print?';?>  

以上代码输出will.
我无法理解它背后的逻辑。谁能解释一下。

提前致谢。

【问题讨论】:

标签: php logic


【解决方案1】:

来自documentation

注意:

建议您避免“堆叠”三元表达式。在单个语句中使用多个三元运算符时 PHP 的行为并不明显:

示例 #4 不明显的三元行为

// 然而,上面的实际输出是't' // 这是因为三元表达式是从左到右计算的

// 下面是与上面相同代码的一个更明显的版本 echo ((true ? 'true' : false) ? 't' : 'f');

// 这里,你可以看到第一个表达式被评估为'true',这 // 反过来计算为 (bool)true,从而返回真正的分支 // 第二个三元表达式。

【讨论】:

    【解决方案2】:

    你应该使用大括号:

    echo true?'what':(true?'will':'print?'); 
    

    这将输出what。如果没有大括号,则第二个 if 覆盖第一个 if。因为三元表达式是从左到右解释的。因此,如果您没有设置任何大括号,PHP 解释器会将您的语句解释为:

    echo (true?'what':true)?'will':'print?'; 
    

    According to PHP.net 你应该避免堆叠三元表达式:

    建议您避免“堆叠”三元表达式。在单个语句中使用多个三元运算符时 PHP 的行为并不明显:

    【讨论】:

      【解决方案3】:

      建议您避免“堆叠”三元表达式。在单个语句中使用多个三元运算符时 PHP 的行为并不明显:(如文档中所示)

      例子:

      `

      on first glance, the following appears to output 'true'
      echo (true?'true':false?'t':'f');
      
      however, the actual output of the above is 't'
      this is because ternary expressions are evaluated from left to right
      
      the following is a more obvious version of the same code as above
      echo ((true ? 'true' : false) ? 't' : 'f');
      
      here, you can see that the first expression is evaluated to 'true', which
      in turn evaluates to (bool)true, thus returning the true branch of the
      second ternary expression.
      

      `

      【讨论】:

        【解决方案4】:

        PHP 中的三元运算符是左结合的。您的代码评估如下:

        echo (true ? 'what' : true) ? 'will' : 'print?';
        

        这相当于:

        echo (true) ? 'will' : 'print?';
        

        因此,结果是“意志”。您应该使用以下内容:

        echo true ? 'what' : (true ? 'will' : 'print?');
        

        相关帖子可以在这里找到:Why is the output of `echo true ? 'a' : true ? 'b' : 'c';` 'b'?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-11
          • 2014-01-21
          相关资源
          最近更新 更多