Originally posted by Weedpacket
Well the definitive, if terse, guide to returning references to variables is of course the manual.
Here's a more elaborate example, though, in which I make $e a reference to a variable with a nondeterministic value inside the function testme:
function &testme()
{ static $a = 0;
$a = microtime();
return $a;
}
$e =& testme();
var_dump($e);
$b =& testme();
var_dump($e);
If $a wasn't made static, its value would be destroyed when the function ended. $e would then become the only variable referencing the value in question, and it wouldn't be updated when testme() was run for the second time (try it!) - the $a in the second run of the function woudl be an entirely separate beast from the $a in the first run.
That's if the static keyword isn't used. Since it is, it is preserved from one run to the next, and $a and $e both reference the same value.
It's actually a peek into how PHP stores variables and values. In a sense all variables are references. PHP keeps a big table of all the variables currently defined, and next to each variable name is a (C-like) pointer into a location in memory where the value is stored. When you say that one variable is a reference of another, what you're saying is that both variables are pointing to the same location in memory; a straight reassignment sees the two variables involved pointing to different memory locations that contain the same value.[*]
It'd help (it helped me) to draw a few diagrams at this point...
Saying that "$a is a reference to $b" (or, equivalently, "$b is a reference to $a") is therefore misleading! Neither is referring to the other; instead they're both referring to the same location in memory.
*That's a good enough description for a first approximation. Needless to say, there are all sorts of opportunities for elaboration and optimisation, and PHP makes many of them (e.g., the symbol table contains typing information); but they're all behind-the-scenes and don't have any visible effect on the above. [/B]