PHP return by reference

We can ask a function return by reference by adding a & before function declare. See example:

function & pass(& $a) {
        return $a;
}

function duplicate(& $a) {
        return $a;
}

$a = array('a'=>'a');
$b = duplicate($a);
$c = & pass($a);
$b['a'] = 'b';
echo $a['a'], "\n";
$c['a'] = 'c';
echo $a['a'], "\n";

output is:

a
c

You will see, the trick here is: don’t forget to put an ‘&’ before the function of assign operation. Otherwise, the assign operation will make a copy of the returned reference.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Share/Bookmark

Leave a Reply