References

Reference binding

  • =&  : Assigns a reference to the rvalue (as opposed to normal assignment, =, which assigns a copy of the rvalue).
  • The right-hand side can be a variable, a call to a function that returns a reference, or the "new" operator (as of PHP 4.0.4).
$aref =& $a;   // Create an alias, $aref, for the value referenced by $a.
$var =& ref_function();
$myobject =& new MyClass();

Reference parameters

function inc(&$value) {
++$value;
}

Returning a reference

function &get_value() {
$value = 1;
return $value;
}
$some_value =& get_value();

Using references with objects

  • Accessing an object without using the & operator causes a copy of the object to be made.
  • $this, used within a class, is a reference to the current instance of the class. The assignment operator without & will copy the instance (the object) and $this will operate on the copy, which is usually not the desired result, functionally or efficiency-wise. 
  • When testing for equality ( == or === ) of objects, PHP 4 performs a completely deep comparison (?). In addition to making sure the references point to the same object, it verifies that all properties of the objects are equal, and if any of the properties are objects, their properties are also verified.  If one of the related objects points to itself directly or indirectly, the program winds up in an infinite loop.

Global references

  • When a variable is declared as "global $var", it's a reference to a global variable.
  • The following examples are equivalent:
global $var;
$var =& $GLOBALS["var"];
  • Unsetting $var won't unset the global variable.

Functions

  • unset()  : Unset the reference (remove the binding between variable name and variable content).