What does a & in front of a variable name mean?
For example &$salary vs. $salary
What does a & in front of a variable name mean?
For example &$salary vs. $salary
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)