6.3. Passing Values by Reference

Problem

You want to pass a variable to a function and have it retain any changes made to its value inside the function.

Solution

To instruct a function to accept an argument passed by reference instead of value, prepend an & to the parameter name in the function prototype:

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

Now there’s no need to return the string because the original is modified in-place.

Discussion

Passing a variable to a function by reference allows you to avoid the work of returning the variable and assigning the return value to the original variable. It is also useful when you want a function to return a boolean success value of true or false, but you still want to modify argument values with the function.

You can’t switch between passing a parameter by value or reference; it’s either one or the other. In other words, there’s no way to tell PHP to optionally treat the variable as a reference or as a value.

Actually, that statement isn’t 100% true. If the configuration directive allow_call_time_pass_reference is enabled, PHP lets you optionally pass a value by reference by prepending an ampersand to the variable’s name. However, this feature has been deprecated since PHP 4.0 Beta 4, and PHP issues explicit warnings that this feature may go away in the future when you employ call-time pass-by-reference. Caveat coder.

Also, if a parameter is declared to accept a value by reference, you can’t pass ...

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.