Occasionally there comes time for you to implicitly return-by-reference.
Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so.
Taken from the PHP Documentation for Returning By Reference.
There are many different forms return by reference can take, including the following example:
function parent(&$var) {
echo $var;
$var = "updated";
}
function &child() {
static $a = "test";
return $a;
}
parent(child()); // returns "test"
parent(child()); // returns "updated"
Return by reference is not only limited to function references. You also have the ability to implicitly call the function:
function &myFunction() {
static $a = 'foo';
return $a;
}
$bar = &myFunction();
$bar = "updated"
echo myFunction();
You cannot directly reference a function call, it has to be assigned to a variable before harnessing it. To see how that works, simply try echo &myFunction();
.
&
) in both places you intend on using it. That means, for your function definition (function &myFunction() {...
) and in the calling reference (function callFunction(&$variable) {...
or &myFunction();
).$a
in the example above. This means you can not return an expression, otherwise an E_NOTICE
PHP error will be generated (Notice: Only variable references should be returned by reference in ......
).