Home » Php » php – What does & sign mean in front of a variable?

php – What does & sign mean in front of a variable?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m ‘dissecting’ PunBB, and one of its functions checks the structure of BBCode tags and fix simple mistakes where possible:

function preparse_tags($text, &$errors, $is_signature = false)

What does the & in front of the $error variable mean?

How to&Answers:

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!

Answer:

It does pass by reference rather than pass by value.

This allows for the function to change variables outside of its own scope, in the scope of the calling function.

For instance:

function addOne( &$val ) {
    $val++;
}
$a = 1;
addOne($a);
echo $a; // Will echo '2'.

In the case of the preparse_tags function, it allows the function to return the parsed tags, but allow the calling parent to get any errors without having to check the format/type of the returned value.

Answer:

It accepts a reference to a variable as the parameter.

This means that any changes that the function makes to the parameter (eg, $errors = "Error!") will affect the variable passed by the calling function.

Answer:

It means that the variable passed in the errors position will be modified by the called function. See this for a detailed look.