将&符号添加到PHP变量的实际用法

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?

$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

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
)

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/

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.

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.