duansaxf095988 2015-04-07 14:39
浏览 14
已采纳

PHP - 正确的三元实现[关闭]

Ok,

so consider the following:

$this->foo = isset($_GET['foo']) && !empty($_GET['foo']) ? $_GET['foo'] : NULL;

and this:

$this->foo = (isset($_GET['foo']) && !empty($_GET['foo'])) ? $_GET['foo'] : NULL;

When I write an if / else statement with multiple checks, I generally include the extra parenthesis as in the second example. In the ternary, both examples work.

Should I add the extra parenthesis as on the bottom? Or go with the first?

Thanks

  • 写回答

3条回答 默认 最新

  • douwen5066 2015-04-07 15:58
    关注

    Operator precedence is the issue as to when parenthesis are necessary (notwithstanding readability).

    When dealing with the ternary operator look at the order PHP uses to group expressions, start with the ternary operator(s) and examine the operators that are grouped after the ternary operator. Those are the operators that have the potential to produce erroneous output.

    PHP Operator Precedence, starting with ternary:

    Assoc.  Operators                   Additional Information
    ...
    left    ? :                         ternary
    right   = += -= *= **= /= .= %=  
            &= %= &= |= ^= <<= >>= =>   assignment
    left    and                         logical
    left    xor                         logical
    left    or                          logical
    left    ,                           many uses
    

    In this case there are the assignment operators, the lower precedence logical operators, and comma.

    It appears the ternary and assignment are equal, therefore grouping is determined by their associativity when the two are in the same statement.

    $a = true? 'yes': 'no';
    // $a is assigned 'yes'
    

    Assignment is right associative so, in relation to the =, expressions are grouped right to left. In this case the ternary comes first (rightmost) and the statement works as expected.

    That leaves the lower precedence boolean and the comma.

    echo true and true? 'yes': 'no';
    // Echos: 1
    // Grouped like: echo true and (true? 'yes': 'no');
    

    Not as expected. Use parenthesis to force intended grouping:

    echo (true and true)? 'yes': 'no';
    // Echos: yes
    

    When using higher precedence boolean operators, which are grouped before the ternary operator, parenthesis are not necessary.

    echo true && true? 'yes': 'no';
    // Echos: yes
    

    Bottom line, when operator precedence is unclear, or readability is desired, use parenthesis.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?