PHP Assign by Reference


Example

This is the first phase of referencing. Essentially when you assign by reference, you're allowing two variables to share the same value as such.

$foo = &$bar;

$foo and $bar are equal here. They do not point to one another. They point to the same place (the "value").


You can also assign by reference within the array() language construct. While not strictly being an assignment by reference.

$foo = 'hi';
$bar = array(1, 2);
$array = array(&$foo, &$bar[0]);

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value.

Assigning by reference is not only limited to variables and arrays, they are also present for functions and all "pass-by-reference" associations.

function incrementArray(&$arr) {
    foreach ($arr as &$val) {
        $val++;
    }
}

function &getArray() {
    static $arr = [1, 2, 3];
    return $arr;
}

incrementArray(getArray());
var_dump(getArray()); // prints an array [2, 3, 4]

Assignment is key within the function definition as above. You can not pass an expression by reference, only a value/variable. Hence the instantiation of $a in bar().