What References DoThere are three basic operations performed using references: assigning by reference, passing by reference, and returning by reference. This section will give an introduction to these operations, with links for further reading. Assign By ReferenceIn the first of these, PHP references allow you to make two variables refer to the same content. Meaning, when you do:
The same syntax can be used with functions that return references:
Using the same syntax with a function that does not return by reference will give an error, as will using it with the result of the new operator. Although objects are passed around as pointers, these are not the same as references, as explained under Objects and references. Warning
If you assign a reference to a variable declared Example #2 Referencing global variables inside functions
global $var; as a shortcut to $var
=& $GLOBALS['var']; . Thus assigning another reference
to $var only changes the local variable's reference.
While not being strictly an assignment by reference, expressions created
with the language construct
Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value. Example:
Pass By ReferenceThe second thing references do is to pass variables by reference. This is done by making a local variable in a function and a variable in the calling scope referencing the same content. Example:
Return By ReferenceThe third thing references can do is return by reference. |