Recipe 6.7 Returning Values by Reference
6.7.1 Problem
You want to return a value by
reference, not by value. This allows you to avoid making a duplicate
copy of a variable.
6.7.2 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);
6.7.3 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.
6.7.4 See Also
Recipe 6.4 on passing values by reference.
|