7

As per the php code below, the output is

1 . 1 
2 . 2 
3 . 3 

I understand &$ref is passing by reference. but its like after the assignment($row = &$ref;) everywhere whenever 'row' changes the value, 'ref' changes as the same value as 'row' too. really confusing. Seems like that = is not only assign the right value to the left. Can someone please verify this?

<?php
$ref = 0;
$row = &$ref;
foreach (array(1, 2, 3) as $row) {
    print "$row . $ref \n" ;
}
echo $ref; 
?>
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
user2381130
  • 193
  • 2
  • 12

2 Answers2

2

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.

1

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.

Machavity
  • 30,841
  • 27
  • 92
  • 100