PHP Functions
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_in_html_tag(&$text, $tag = 'strong') {
$text = "<$tag>$text</$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.
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.
No comments:
Post a Comment