dshdb64088 2014-09-09 21:52
浏览 292
已采纳

嵌套三元运算符的优先顺序

I was in class the other day and this snippet of code was presented:

 <?php
 //Intialize the input
 $score=rand(50,100);
 //Determine the Grade
 $grade=($score>=90)?'A':(
 ($score>=80)?'B':(
 ($score>=70)?'C':(
 ($score>=60)?'D':'F')));
 //Output the Results
 echo "<h1>A score of $score = $grade</h1>";
 ?>

At the time I questioned the order of operations within the nested ternary operators, thinking that they would evaluate from the inside out, that is it would evaluate if $score were >= 60 first, then if $score >= 70, etc -- working through the whole stack every time regardless of the score.

To me it seems that this construct should follow the same order of precedence given to mathematical operators -- resolving the inner-most set of parentheses first and then working out, unless there is some order of operations unique to the ternary.

Unfortunately the discussion in class quickly became about winning an argument, when I really just wanted to understand how it works. So my questions are two:

(1)How would this statement me interpreted and why?

and

(2)Is the some sort of stack trace or step through tool that would allow me to watch how this code executes?

  • 写回答

4条回答 默认 最新

  • dongwo5110 2014-09-09 22:09
    关注

    PHP respects brackets. Expressions inside the innermost ( ... ) are evaluated first, like we are taught in elementary school.

    PHP is unusual in that ternary operators are left-associative. This means without brackets, the ternary expression is evaluated left to right.

    But in this particular case, the brackets force the expression to be evaluated right to left. This code is equivalent to:

    if ($score >= 90) {
        $grade = 'A';
    }
    elseif ($score >= 80) {
        $grade = 'B';
    }
    elseif ($score >= 70) {
        $grade = 'C';
    }
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号