PHP: What does a & in front of a variable name mean?

Php

Php Problem Overview


What does a & in front of a variable name mean?

For example &$salary vs. $salary

Php Solutions


Solution 1 - Php

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'
?>

Solution 2 - Php

It's a reference, much like in other languages such as C++. There's a section in the documentation about it.

Solution 3 - Php

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)

Solution 4 - Php

It is used to pass a variable by reference.

Read more in the PHP documentation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionfunk-shunView Question on Stackoverflow
Solution 1 - PhpRandy the DevView Answer on Stackoverflow
Solution 2 - PhprmeadorView Answer on Stackoverflow
Solution 3 - PhpTahazzotView Answer on Stackoverflow
Solution 4 - PhpSam DayView Answer on Stackoverflow