Passing by reference php link
As per the below php code, the output is
1 . 1
2 . 2
3 . 3
I understand & $ ref is passed by reference. but as after the assignment ($ row = & $ ref;) wherever "row" changes a value, "ref" is changed to be the same value as "row". really confusing. It looks like = is not only assigning the correct value to the left. Can anyone confirm this?
<?php
$ref = 0;
$row = &$ref;
foreach (array(1, 2, 3) as $row) {
print "$row . $ref \n" ;
}
echo $ref;
?>
source to share
Without getting into the technical details , the main idea here is what you $ref
referenced to $row
. In particular, it $row
is located at some memory address. If you are doing a simple assignment
$ref = $row;
Then $ref
is a copy $row
. If you change one it won't change the other
$row = &$ref;
$ref
now points to $row
. Thus, they are essentially the same variable. They point to the same memory location (simplistic, so you get the idea).
The most common is that you need to insert some value into a function.
$data = ['1', '2', '3'];
function modVal(Array &$arr) {
$arr[2] = '9';
}
modVal($data);
var_dump($data);
Issues
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "9"
}
Remove &
from function declaration however the output will be
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
PHP is sometimes automatically passed by reference. For example, if you instantiate a class and inject it into a function, it is automatically passed by reference.
source to share