What does & sign mean before a variable?

I "dissect" PunBB, and one of its functions checks the BBCode tag structure and captures simple errors where possible:

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

What does & mean before the $error variable?

+6
php punbb
source share
4 answers

This means passing the variable by reference , rather than passing the value of the variable. This means that any changes to this 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:

Without changes

Without changes

Changed!

+22
source share

It passes only by reference, not by value.

This allows the function to modify variables outside its scope, in the scope of the calling function.

For example:

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

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

+2
source share

It takes a variable reference as a parameter.

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

+1
source share

This means that the variable passed to the error position will be changed by the called function. See this for more details.

0
source share

All Articles