php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #12247 ternary ?: loses references
Submitted: 2001-07-19 07:02 UTC Modified: 2002-09-14 19:34 UTC
From: nick at macaw dot demon dot co dot uk Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 4.2.1 OS: Solaris
Private report: No CVE-ID: None
 [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



Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-09-14 06:03 UTC] Xuefer at 21cn dot com
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: ++ -- += -= *= /=
 [2002-09-14 11:57 UTC] nick at macaw dot demon dot co dot uk
Agreed. Returning a reference to $x + 2 is a nonsense, and accordingly ?: falls into the same category. The case I quoted was really a special one. Making a change from Sniper doing it (sorry mate :), I'm happy for someone to bogossify this one.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 12:01:27 2024 UTC