6.6. Returning Values by Reference

Problem

You want to return a value by reference, not by value. This allows you to avoid making a duplicate copy of a variable.

Solution

The syntax for returning a variable by reference is similar to passing it by reference. However, instead of placing an & before the parameter, place it before the name of the function:

function &wrap_html_tag($string, $tag = 'b') {
    return "<$tag>$string</$tag>";
}

Also, you must use the =& assignment operator instead of plain = when invoking the function:

$html =& wrap_html_tag($string);

Discussion

Unlike passing values into functions, in which an argument is either passed by value or by reference, you can optionally choose not to assign a reference and just take the returned value. Just use = instead of =&, and PHP assigns the value instead of the reference.

See Also

Recipe 6.4 on passing values by reference.

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.