Variables in PHP: Assign by reference

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
?>
  • This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable.
  • Changes to the new variable affect the original, and vice versa.
  • To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable).
  • Only named variables may be assigned by reference.

Related concepts

Assign by reference

Variables in PHP: Assign by reference — Structure map

Clickable & Draggable!

Variables in PHP: Assign by reference — Related pages: