Reference assignment operator ( =& ) combined with passed by reference ( &$var ) in PHP

Why is the variable passed by reference not changed when the assignment is also made with a reference?

function foo(&$x) {
    $y = 1;
    $x = &$y;
}
$bar = 0;
foo($bar);
echo $bar; //why is this not 1?

This behavior seems to be identical in all PHP versions. Therefore I assume that the behavior is by design.

Is it documented somewhere that the reference is lost in such cases?


Solution 1:

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on. [..] Instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.

What References Are

<?php
$a =& $b;
?>

it means that $a and $b point to the same content.

Note:
$a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place.

What References Do

So, $x = &$y; makes $x an alias of the value that $y is pointing to. If $x was an alias to some value before, that's broken now, because it can only point to one value at a time.

However, it feels wrong that you can destroy the passed by reference relationship.

Well, that's entirely up to you. If you understand how references work, then you are entirely in control of writing code that makes them work as you want them to.