Recipe 6.3. Passing Values by Reference


6.3.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.3.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.3.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.

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.3.4. See Also

Recipe 6.6 on returning values by reference.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net