start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

6.4. Passing Values by Reference

6.4.1. Problem

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

6.4.2. 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.

6.4.3. 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 a constant string (or number, etc.), or PHP will die with a fatal error.

6.4.4. See Also

Recipe 6.7 on returning values by reference.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.