Incorporating External Variables into Anonymous Function Parameters
In programming, it's often necessary to access variables defined outside the scope of a function. When utilizing anonymous functions as parameters, this task can be challenging.
Let's consider the following scenario: a function, fetch(), is used to process database rows and pass them to an anonymous function as a parameter. Each row can be accessed using $r['title'], but the requirement arises to concatenate these titles into a variable.
While the global modifier can be employed, it's not an elegant solution. A more appropriate approach is to use the use keyword, as demonstrated in the following code:
$result = ''; fetch("SELECT title FROM tbl", function($r) use (&$result) { $result .= $r['title']; });
The use keyword captures the external variable result by reference (&$result) and makes it available within the anonymous function.
Note, however, that use() parameters exhibit early binding. This means they use the variable's value at the point of lambda function declaration, not at the point of invocation (late binding).
The above is the detailed content of How to Access External Variables Within Anonymous Function Parameters in PHP?. For more information, please follow other related articles on the PHP Chinese website!