Return by Reference

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents