Using Anonymous Functions as Parameters to Access External Variables
The scenario involves a handy function that conveniently processes database rows. However, a specific requirement arises where you need to concatenate all titles from the result set into a single variable. This raises the question of how to accomplish this without relying on the less elegant approach of using the global keyword.
One solution lies in the use of closure variables. Specifically, the use keyword allows closures to inherit variables from the parent scope. This is different from global variables, which persist across all functions.
To implement this solution, the code can be modified as follows:
$result = ''; fetch("SELECT title FROM tbl", function($r) use (&$result) { $result .= $r['title']; });
By adding use (&$result) to the anonymous function, we are able to reference and modify the result variable from within the function. The use keyword effectively passes a reference to the result variable to the closure.
It's important to note that this approach involves early binding, which means that the closure uses the value of the variable at the point of function declaration, not at the point of function call (late binding). This is something to keep in mind when utilizing closures for this purpose.
The above is the detailed content of How can I access and modify external variables within an anonymous function in PHP?. For more information, please follow other related articles on the PHP Chinese website!