【问题标题】:ternary operator with ampersand [duplicate]带与号的三元运算符[重复]
【发布时间】:2015-09-24 21:43:24
【问题描述】:

我在代码中的某处使用了跟随:

if (isset($flat[$pid])) {
  $branch = &$flat[$pid]['items'];
} else {
  $branch = &$tree;
}    

一切正常,但是当我想将其缩短为:

$branch = isset($flat[$pid]) ? &$flat[$pid]['items'] : &$tree;

我明白了:

语法错误,意外的'&' ...

我做错了什么?

【问题讨论】:

标签: php syntax pass-by-reference ternary-operator


【解决方案1】:

这是因为ternary operator 是一个表达式,所以它不会计算为变量。并引用手册:

注意:请注意,三元运算符是一个表达式,它不会计算为变量,而是计算表达式的结果。了解是否要通过引用返回变量很重要。语句 return $var == 42 ? $a : $b;因此,在按引用返回的函数中将不起作用,并且在以后的 PHP 版本中会发出警告。

【讨论】:

    【解决方案2】:

    这将作为替代方案,

    (isset($flat[$pid])) ? ($branch = &$flat[$pid]['items']) : ($branch = &$tree);
    

    编辑:

    最短可以走两行,

    @$temp = &$flat[$pid]['items'];
    $branch = &${isset($flat[$pid]) ? "temp" : "tree"};
    

    【讨论】:

    • 非常神秘:) 在这种情况下我更喜欢if 子句。
    猜你喜欢
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2020-05-21
    • 2015-04-04
    • 2019-07-14
    • 2011-05-05
    • 2014-09-29
    • 2012-07-23
    相关资源
    最近更新 更多