|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-05-15 22:59 UTC] dukeofgaming at gmail dot com
Description:
------------
PHP fails to parse a returned by reference value when using the ternary operator.
The test script provided illustrates a case of when it is absolutely necessary
to return by reference; if the "&" is removed then the output would be a fatal
error: "Fatal error: Cannot use [] for reading in <...>"
Test script:
---------------
$value = ($condition)?(
$some_value
):(&$object->Collection[]);
Expected result:
----------------
No errors, should be the equivalent of having:
if($condition){
$value = $some_value;
}else{
$value = &$object->Collection[];
}
Actual result:
--------------
Parse error: syntax error, unexpected '&' in <...>
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Nov 02 19:00:02 2025 UTC |
I thoroughly read the article you mentioned, Mike, but still don't understand why the following code fails to compile: $link = isset($i) ? (& $arr[$i]) : null; - while the following works fine: $link = &$arr[$i]; In this case, &$arr[$i] is a legal reference assignment, so the first code should behave equal to if (isset($i)) { $link = &$arr[$i]; } else { $link = null; } - but this code works fine, and mentioned above isn't even compiled. What's wrong with it?Mike, I understand that. The second note tells I caanot return a reference to an expression result, such as &$object->method() or &(new StdClass()) - I can understand that. But the code sample I provided doesn't try to do that. To make things even simplier, the following code still fails to compile: $link = $flag ? &$a : &$b; It doesn't try to return a reference to an expression, just a reference to a viriable; It doesn't try doing anything that the following code doesn't: if ($flag) $link = &$a; else $link = &$b; And maybi I'm really stupid, but after 10 years in PHP development I still don't understand why the first code cannot be compiled :(