2

I know that prepending a '&' to your PHP variable sets up a reference to the original variable instead of copying its value like so:

$original = 'apples';
$secondary = &$original;
$original = 'oranges';

echo $secondary; // 'oranges'

If it works this way, why not just use the original variable then?

enchance
  • 29,075
  • 35
  • 87
  • 127
  • 4
    This might help: [When do I use Pass by Reference in PHP?](http://stackoverflow.com/questions/5479073/when-do-i-use-pass-by-reference-in-php) – Sean Walsh May 24 '11 at 16:31
  • Point of interest: Internally, every duplicate of a variable in PHP is actually a reference, until you try and change its contents. Its then copied and modified at that point. – berty May 24 '11 at 16:54
  • @berty: is that optimization part of the language specification or part of the implementations you're aware of? If the first, it's a useful piece of knowledge. If not, you can only trust it to optimize the specific version of PHP that you're running on, not treat it as a safe language assumption. – Tetsujin no Oni Dec 02 '11 at 06:11
  • I can't at this point find anything to support or refute that, but I am sure I heard it somewhere. I think its an optimisation in the language, but not 100%. Sorry! – berty Dec 07 '11 at 17:54

5 Answers5

2

Passing by reference is useful and necessary when passing a variable as a parameter to a function, expecting that variable to be modified without a copy being created in memory. Many of PHP's native array_*() functions operate on array references, for example.

This function, for example, receives an array reference and appends an element onto the original array. If this was done without the & reference, a new array copy would be created in scope of the function. It would then have to be returned and reassigned to be used.

function add_to_an_array(&$array)
{
  // Append a value to the array
  $array[] = 'another value';
}

$array = array('one', 'two', 'three');
add_to_an_array($array);

print_r($array);

Array
(
  [0] => one
  [1] => two
  [2] => three
  [3] => another value
)
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • 2
    The drawback to making a variable a reference is that one the reference is established, it's maintained throughout the life of that variable. If you reuse a variable in multiple sections of a script, you can end up with hard-to-diagnose bugs as you're now resetting variables you don't expect to be, in different sections of code. – Marc B May 24 '11 at 17:01
  • Also, make sure you document the fact that a function receives a parameter by reference, so the caller knows exactly what's happening. – rid May 24 '11 at 17:09
1
$original = 'apples';

function foo($word) {
    $word = 'oranges';
}

foo($original);
echo $original; // apples, because only local $word was changed, not $original.

foo(&$original);
echo $original; // oranges, because $original and $word are the same
Amy B
  • 17,874
  • 12
  • 64
  • 83
  • So basically what you're saying is I can use this instead of adding a `global $original` inside the function. Am I correct in saying so? – enchance Dec 01 '11 at 17:48
1

Pass by reference is really a cop out and goes against good encapsulation. If you need to manipulate a variable in that way, it probably should belong to a class as a member variable and then does not need to be passed to the function. Good OO design would usually make member variables immutable with a "final" keyword, but PHP doesn't have this. It's not intuitive that passing a variable to a function might change it's value which is why it should be avoided in most cases.

Also going to a more full OO design prevents you have having method signatures that are long and complex with many optional parameters that are difficult to re-factor.

FoneyOp
  • 336
  • 1
  • 6
  • 1
    However, many of the PHP core functions have implicit call-by-reference, such as the various array sorting functions (asort, ksort, etc...). Pass-by-reference is the only way to accomplish that kind of in-place sorting. – Marc B May 24 '11 at 17:00
  • If you are creating a function of this type pass by reference might make sense over say a utility class. However, 98% of most programming tasks are not creating xsort() functions but are creating business logic and object models. In these majority of cases a solid OO design can usually eliminate the need for complex method signatures and create more readable and maintainable code. – FoneyOp May 24 '11 at 17:05
  • PHP's is not, by any stretch, a complete OO implementation. It has lots of legacy procedural bits that will stick around for years to come. Most of PHP's array operations are pass by reference, and reimplementing them as classes isn't helpful in the short term. – Michael Berkowski May 24 '11 at 17:06
  • PHP supports all the core OO constructs. It doesn't follow that just because PHP doesn't have collections, therefore developers should not design their application using those constructs. If you design a class method that uses ksort($foo) instead of foo.sort() it does not mean that the application is not OO or can not be designed that way. – FoneyOp May 24 '11 at 17:59
  • I concur. While it may work to serve some purpose, pass by reference offers in most every case possible an inferior alternative to some better design. – Mario May 18 '15 at 15:20
0

There are many uses for references.

  • You can pass a reference to a variable to a function so you can change the value inside the function
  • You can use references to create linked lists

etc...

Just keep in mind that they're there, and you'll surely find an application for them when the time comes and you face a problem that can be solved with references.

Check out the following article for other ideas and uses of references: http://www.elated.com/articles/php-references/

rid
  • 61,078
  • 31
  • 152
  • 193
  • [This question](http://stackoverflow.com/questions/6102887/return-large-data-by-reference-or-as-return-in-function) points out that using references for large variables actually leads to more copying (and more memory usage) in the C code. PHP already tries to optimize variable/reference assignments. – Paul DelRe May 24 '11 at 16:38
  • Interesting... Thanks for pointing that out. Will investigate. – rid May 24 '11 at 16:44
0

A more interesting use of the is when it's used in the formal argument to a function

foo($a);

...

function foo (&$a) { .... }

this allows you to modify a in the function.

Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83