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

3 Responses to “PHP return by reference”

  1. Kasha Fink Says:

    Hi! I enjoy your website but I’m having trouble getting it to render correctly in the Konqueror browser. You might want to recheck your css. Thanks! :)

  2. Panda Internet Security 2010 Says:

    hello there, i just saw your site via bing, and i must comment that you compose pretty well on your website. i am truly moved by the way that you write, and the subject is superb. anyhow, i would also love to acknowledge whether you would like to exchange links with my site? i will be more than willing to reciprocate and insert your link off in the link exchange area. looking for your answer, thanks and have a great day!

  3. freecause Says:

    Usually I do not post on blogs, but I would like to say that this article really forced me to do so! Thanks, really nice article.

Leave a Reply