| 
        php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
  [2001-07-19 07:02 UTC] nick at macaw dot demon dot co dot uk
 This may be a subtlety of the ?: operator that I failed to spot - then again it may just be a bug.
Using ?: with references loses the reference, as the example below illustrates.  In both cases a reference to the second argument to a function should be returned, the result modified and the original argument displayed. The expectation being that it has now changed. When the reference is returned from and if-then-else statement all is fine. When the reference is, or isn't?, returned from ?: the result is not as expected.
The output from the code is
[1] [xx]
[1] [2]
function &return_ref(&$arg1, &$arg2, $cond)
{
   if ($cond) { return $arg1; } else { return $arg2; }
}
function &return_ref_ternary(&$arg1, &$arg2, $cond)
{
   return ($cond ? $arg1 : $arg2);
}
$arg1 = '1'; $arg2 = '2';
$res =& return_ref($arg1, $arg2, false);
$res = 'xx';
echo "[$arg1] [$arg2]\n";
$arg1 = '1'; $arg2 = '2';
$res =& return_ref_ternary($arg1, $arg2, false);
$res = 'xx';
echo "[$arg1] [$arg2]\n";
-- nick
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             
             | 
    |||||||||||||||||||||||||||
            
                 
                Copyright © 2001-2025 The PHP GroupAll rights reserved.  | 
        Last updated: Tue Nov 04 13:00:02 2025 UTC | 
i don't think is as a bug, but a feature request "?:" is operator and "($cond ? $arg1 : $arg2)" is actually an expression not variable imagine how can one return expression like function &return_ref() { return $arg1 + 1; } and how about function &return_ref() { return $arg1 ++; } also for operators: ++ -- += -= *= /=