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 Unity3D WebView
  • ¥20 论文AlphaTensor复现(有偿)
  • ¥15 (有偿)在ANSYS中 .anf文件
  • ¥45 关于#芯片#的问题:组合逻辑电路设计
  • ¥15 基与机器学习和时间序列分析预测养老服务需求趋势
  • ¥100 求连续两帧图像在水平和垂直上偏移
  • ¥15 mysql全文索引查找指定必须关键词word无效
  • ¥15 Verilog hdl密码锁设计
  • ¥35 基于python的有ssl加密传输的socket聊天室
  • ¥15 数码管亮度控制器设计