【问题标题】:what is the difference between these two lines [duplicate]这两行有什么区别[重复]
【发布时间】:2016-07-06 13:41:39
【问题描述】:

在使用相同的货币“egp”时获得 2 个不同的输出

$currency = ($q->currency == 'egp')? '£' : (($q->currency == 'usd') ? '$' : '€');

这一行输出$

$currency = ($q->currency == 'egp')? '£' : ($q->currency == 'usd') ? '$' : '€';

这个输出£

我找不到原因?

注意:唯一的区别是第二个三元运算符语句周围的()

【问题讨论】:

  • 去掉多余的()会导致运算符的优先级发生变化。如果你需要做这种事情,我通常建议切换到if elseif else 标准语法,以便于使用、可读性和理解性。
  • 三元运算非常棒,用于简短的检查。嵌套三元运算应该是非法的。

标签: php conditional-operator


【解决方案1】:

考虑这段代码:

echo (true?"Left is first":(true?"Right is first":""));

左边是第一

对比

echo (true?"Left is first":true?"Right is first":"");

权利是第一

解释可以在http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary找到。

简而言之,在第二种情况下,PHP 将评估 true?"Left is first":true 作为三元表达式的条件。这将评估为 Left is first,其评估结果为 true,因此 Right is first 将被回显

【讨论】:

    猜你喜欢
    • 2019-12-29
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 2021-10-17
    • 2013-04-29
    • 2017-02-02
    相关资源
    最近更新 更多