The note by zayfod below is very misleading. The following is not true:
"You do not have to use & to indicate that reference binding should be done when you assign to a value passed by reference the result of a function which returns by reference."
As proof, you can change zayfod's second example slightly to show that $var does not, as he claims, become a reference to $some_var.
<?php
class some_class
{
function & func_b ()
{
$this->some_var = 2;
return $this->some_var;
}
function func_a (& $param)
{
# $param is 1 here
$param = $this->func_b();
# $param is 2 here
}
}
$var = 1;
$object = new some_class();
$object->func_a($var);
print $var; // this prints two
$var = 5;
print $object->some_var;
// $object->some_var is still 2, because $var is not bound to it
// (as the original post by zayfod claims) and therefore has no
// effect on it
?>
In actuality it is impossible to bind a variable passed by reference to a variable returned by reference, doing so only removes the link between the internal parameter variable and binds it to something new. This is why zayfod's first example shows $var having a value of 1 at the end. What is actually happening in zayfod's first example is the following:
1) $var is passed by reference into func_a, which binds $param to $var
2) func_b is evaluated, returning a reference to $some_var
3) $param is bounded to $some_var therefore losing it's binding to $var
4) func_a returns, with $var unchanged
In the second example step 1 and 2 are the same, but then this happens:
3) the value 2 is copied into $param, which still references $var, and therefore $var now also evaluates to 2
4) func_a returns, $var is 2, but is not bound to $some_var (and wouldn't be even in my example where some_var still exists afterward)
The mistake seems to be based on misuse of references. When you return a reference, it means that you want a variable that is tied to another, so that when you change one, the other one changes. In zayfod's example, returning by reference is pointless, because $some_var ceases to exist after the function is completed, it won't stay tied to anything.
There are two ways to change those functions so that in the end you have $var actually bound to $this->some_var:
1) Pass $param into func_b by reference and reference $this->some_var to func_b's parameter like so:
func_b (&$b_param)
{
$this->some_var =& $b_param; // be careful not to flip this
$this->some_var = 2;
}
2) change func_a to return the result of func_b by reference, and reference that to $var
And remember this simple rule: If a variable is already referenced to another variable and you reference it to a third (put it on the left side of =&) it loses its original reference. This is what happens to $param in zayfod's example. (Also don't forget that passing by reference actually references the internal parameter variable to the the passed variable.)