Passing by reference assignment php
This question already has an answer here:
Without delving into the technical details too much, the basic idea here is that you have made $ref
a reference to $row
. Specifically, $row
is at some memory address. If you do a simple assignment
$ref = $row;
Then $ref
is a copy of $row
. If you change one, it will not change the other
$row = &$ref;
$ref
now points to $row
. So they are, essentially, the same variable. They point to the same memory location (oversimplified so you get the idea).
The most common use is that you need to inject some value into a function.
$data = ['1', '2', '3'];
function modVal(Array &$arr) {
$arr[2] = '9';
}
modVal($data);
var_dump($data);
Produces
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "9"
}
Remove the &
from the function declaration, however, and the output becomes
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
PHP will sometimes automatically pass by reference for you. For instance, if you instantiate a class and inject that instance it into a function, it will be passed by reference automatically.
When you do $row = &$ref;
It means: the same variable content with another name. That is, the same, not a copy. What you do in $ref
, it will be made in $row
... and vice versa.
上一篇: 用简单的术语解释PHP / MySQL
下一篇: 通过引用分配php