问题
Why isn't this working?
$a = 'FOO';
$foo = $a ? &$a : 'whatever'; // <- error here
echo $foo;
I get a parse error :|
回答1:
If you want to assign a reference using a ternary statement, then you need this clumsy workaround:
list($foo) = $a ? array(&$a) : array('whatever');
However, as said in the other answers, this seldomly saves memory.
回答2:
Although you tagged your question if-statement, that's not an if statement, it's a ternary conditional expression. I've retagged it accordingly.
Now, the reason why it doesn't work is because assigning by reference is different from assigning normal value expressions in PHP. You can't use references with the ?:
operator in the same way you can't do return &$foo;
in a function. See these manual pages about PHP references for more:
- What References Do
- Returning References
If you use an actual if statement, it'll work:
if ($a)
$foo = &$a;
else
$foo = 'whatever';
But why you'd want to use references like this is beyond me (unless this is PHP 4, and even then you shouldn't be using PHP 4 anymore).
回答3:
Try this:
$a ? $foo = &$a : $foo = 'whatever';
来源:https://stackoverflow.com/questions/5931680/ternary-operator-not-working-with-reference-variables-in-php