12
function fun1();
function &fun1();

What is the difference between these??

Joe Smack
  • 465
  • 1
  • 7
  • 16

2 Answers2

18

If you put an ampersand before your function name, the function will return a reference to a variable instead of the value.

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so.

From the PHP Manual on Returning References.

Evan Mulawski
  • 53,455
  • 14
  • 114
  • 144
  • so if I return by reference (say $var = fun(123) ) does that mean when I change $var, then it actually changes the variable inside the function (the variable inside fun)? – Joe Smack Dec 04 '10 at 19:23
  • The reference will point to the same memory address. When you modify the reference, you also modify the original object. – Evan Mulawski Dec 04 '10 at 19:30
  • This site may help, as well: http://www.elated.com/articles/php-references/ – Evan Mulawski Dec 04 '10 at 19:39
5

The difference is how the return value is returned: Without & the return value is returned by value and with & the return value is returned by reference.

The latter implies that you need to use a variable in the return statement as you can only reference variables.

Gumbo
  • 620,600
  • 104
  • 758
  • 828