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:
<?php
The same syntax can be used with functions that return references, and with the new operator (since PHP 4.0.4 and before PHP 5.0.0):
<?php E_DEPRECATED message in PHP 5.3 and
later, and an E_STRICT message in earlier versions.
(Technically, the difference is that, in PHP 5, object variables, much like
resources, are a mere pointer to the actual object data, so these object
references are not "references" in the same sense used before (aliases).
For more information, see Objects
and references.)
Warning
If you assign a reference to a variable declared global inside a function, the reference will be visible only inside the function. You can avoid this by using the $GLOBALS array. Example #2 Referencing global variables inside functions
<?php
While not being strictly an assignment by reference, expressions created with the language construct array() can also behave as such by prefixing & to the array element to add. Example:
<?php 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:
<?php 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:
<?php Return By ReferenceThe third thing references can do is return by reference. |