4

What does "&" mean in '&$var' in PHP? Can someone help me to explain this further. Thank you in advance.

frogcoder
  • 354
  • 5
  • 19

2 Answers2

13

It means pass the variable by reference, rather than passing the value of the variable. This means any changes to that parameter in the preparse_tags function remain when the program flow returns to the calling code.

function passByReference(&$test) {
    $test = "Changed!";
}

function passByValue($test) {
    $test = "a change here will not affect the original variable";
}

$test = 'Unchanged';
echo $test . PHP_EOL;

passByValue($test);
echo $test . PHP_EOL;

passByReference($test);
echo $test . PHP_EOL;

Output:

Unchanged

Unchanged

Changed!
Tanjima Tani
  • 580
  • 4
  • 18
2

You can pass a variable to a function by reference. This function will be able to modify the original variable.

You can define the passage by reference in the function definition with &

for example..

<?php
function changeValue(&$var)
{
    $var++;
}

$result=5;
changeValue($result);

echo $result; // $result is 6 here
?>

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition.

coDe murDerer
  • 1,858
  • 4
  • 20
  • 28