Saturday, March 24, 2007

What References Are and What Reference Do

References in PHP are a means to access the same variable content by different names. They are not like C pointers; 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 most close analogy is with Unix filenames and files - variable names are directory entries, while variable contents is the file itself. References can be thought of as hardlinking in Unix filesystem.

PHP references allow you to make two variables to refer to the same content. Meaning, when you do:


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

it means that $a and $b point to the same content.
Note: $a and $b are completely equal here, that's not $a is pointing to $b or vice versa, that's $a and $b pointing to the same place.
Unsetting References

When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:

<?php
$a = 1;
$b =& $a;
unset($a);
// OR
$a = 1;
$b =& $a;
$b = NULL;
?>

won't unset $b, just $a.
Again, it might be useful to think about this as analogous to Unix unlink call.

$thisIn an object method, $this is always a reference to the caller object.

No comments :