Assign by Reference

suggest change

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().

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


References:
* Assign by Reference

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
55 References
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR