Accessing External Variables within Callback Functions
In PHP, it is often necessary to utilize callback functions in conjunction with variables calculated outside of the function's scope. This scenario raises the question: Is it possible to access such variables within the callback?
The Use Keyword and Arrow Functions
Fortunately, PHP provides a solution through the use keyword. You can inherit variables from the parent scope by prefacing the callback definition with use. For instance:
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $avg = array_sum($arr) / count($arr); $callback = function($val) use ($avg) { return $val < $avg; }; return array_filter($arr, $callback);
For PHP versions 7.4 and later, arrow functions offer a more elegant approach. Arrow functions automatically capture outside variables:
$callback = fn($val) => $val < $avg;
Within the array_filter call, you can directly utilize the arrow function:
return array_filter($arr, fn($val) => $val < $avg);
By leveraging the use keyword or arrow functions, it becomes straightforward to access external variables within callback functions in PHP.
The above is the detailed content of How Can I Access External Variables Inside PHP Callback Functions?. For more information, please follow other related articles on the PHP Chinese website!