Search code examples
phppunbb

What does & sign mean in front of a variable?


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?


Solution

  • 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!