Trying to understand references

Hi! I am very confused with references…
As far as I understand after reading lot of theory when you pass variables by reference to a function then the function can modify the values of variables outside the function scope…

Then…

<?php
function a(&$a, &$b) { 
$a =& $b; 
}
$a = 1;
$b = 2;
a($a, $b);
$b = 3;
print $a;
?>

Why this code outputs “1”??

I mean…

<?php
function a($a, $b) { // now references are gone here 
$a =& $b; 
}
$a = 1;
$b = 2;
a($a, $b);
$b = 3;
print $a;
?>

Outputs “1”

So… question is… what does exactly do & when declaring function a(&$a, &$b)??

Thanks a lot!!

When function executes $a and $b are aliases for some external variables.
The code $a = &$b; make $a be an alias for $b, but due to fact that $b is an alias either, $a becomes an alias of the same external variable that $b is an alias for. So since this point local $a has nothing to do with global $a.

Look at my description here , it may help you.

http://swarajketan.com/2010/07/01/passing-by-reference-in-php5/

This is because of the way PHP deals with references. They aren’t the same as pointers in other languages, but more like aliases. Basically, you can’t rebind $a inside the local scope of the function. If you remove the & from either the assignment, or the parameter $b then it will do what you expect.

As I understand it, PHP creates a new symbol table for the function (and destroys on exit). &$a and &$b in your function are local variables that point to other variables. When you assign $a = &$b you are telling $a to be a reference to the local $b, so the global $a still exists as 1, and the local alias $a that was pointing to the global $a now points to the local $b (which is pointing at the global $b). Both of these will be destroyed when the function returns.

Someone posted a great link a while ago that explained it far better than I could, sorry I didn’t bookmark.

http://www.php.net/manual/en/language.references.whatdo.php
http://www.php.net/manual/en/language.references.pass.php