6.3.1. ProblemYou want to pass a variable to a function and have it retain any changes made to its value inside the function. 6.3.2. SolutionTo 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. DiscussionPassing 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 AlsoRecipe 6.6 on returning values by reference. |