|
PHP referencesPosted: May 31, 2007 Last modified: Apr 27, 2018This article looks at how to use references in PHP 4. As PHP 4 handles references in a quirky and unique way, this is something all PHP coders should get to grips with! The "&" operator is used to indicate that a variable should be assigned or passed by reference, depending on the context. References in PHP are not like pointers in C. Instead, references are used to make variable names aliases of other variable names, so that they both refer to the same contents. Assignment by referenceWhen a variable is assigned to another variable, it is actually assigned to a copy of the value of the variable (at least from the programmer's point of view; the PHP interpreter can make optimizations so that a copy is only made when it is actually needed). Consider the following snippet: $a = 100;
$b = $a;
$a++;
At the end of the snippet, the value of $a = 100;
$b =& $a;
$a++;
Now, the value of both In PHP 4, when you use " $myObj = new MyClass();// Creates copy of new object
$myObj =& new MyClass();// Returns reference of new object
Note that using " Pass by referenceWhen a function is to modify a variable that is passed to it, it should be passed by reference - otherwise, a local copy of the variable will be made in the function and the changes won't affect the variable passed from outside. To indicate that a function should accept a reference as an argument, use the " bool sort ( array &$array [, int $sort_flags] )
If you pass an array with the elements 3, 2, 1 to $a = array(3, 2, 1);
sort($a);
print_r($a);
Outputs: Array
(
[0] => 1
[1] => 2
[2] => 3
)
Notice that you do not need to include the " Return a reference from a functionIn PHP 4, all functions that return an object should do so by reference - otherwise a copy of the object, possibly just created in the function, is needlessly returned instead. To indicate that a function should return a reference, prefix the function name with a " function &getPerson($personID)
{
$person =& new Person($personID);
return $person;
}
$person =& getPerson(123);
Notice that the assignment of the reference returned by getPerson() still needs to use the " |