PHP Return by Reference


Example

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();.


Notes

  • You are required to specify a reference (&) 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();).
  • You can only return a variable by reference. Hence the instantiation of $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 ......).
  • Return by reference does have legitimate use cases, but I should warn that they should be used sparingly, only after exploring all other potential options of achieving the same goal.