带符号的三元运算符

ternary operator with ampersand

我在代码中的某处使用 followed:

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

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

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

我得到:

syntax error, unexpected '&' ...

我做错了什么?

这是因为 ternary operator 是一个表达式,所以它的计算结果不是变量。以及手册中的引述:

Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

这将作为替代方案,

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

编辑:

最短可以走两行,

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