PHP: What does a & in front of a variable name mean?
What does a &
in front of a variable name mean?
For example &$salary
vs. $salary
It passes a reference to the variable so when any variable assigned the reference is edited, the original variable is changed. They are really useful when making functions which update an existing variable. Instead of hard coding which variable is updated, you can simply pass a reference to the function instead.
Example
<?php
$number = 3;
$pointer = &$number; // Sets $pointer to a reference to $number
echo $number."<br/>"; // Outputs '3' and a line break
$pointer = 24; // Sets $number to 24
echo $number; // Outputs '24'
?>
It's a reference, much like in other languages such as C++. There's a section in the documentation about it.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:
$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.
One important thing to note is that only named variables may be assigned by reference.
$foo = 25;
$bar = &$foo; // This is a valid assignment.
$bar = &(24 * 7); // Invalid; references an unnamed expression.
function test()
{
return 25;
}
$bar = &test(); // Invalid.
Finally, While getting a reference as a parameter, It must pass a reference of a variable, not anything else. Though it's not a big problem because we know why we are using it. But It can happen many times. Here's how it works:
function change ( &$ref ) {
$ref = 'changed';
}
$name = 'Wanda';
change ( $name ); // $name reference
change ( 'Wanda' ); // Error
echo $name; // output: changed
README (for more information)