使用外部计算的变量的回调函数
基本上我想做这样的事情:
Basically I'd like to do something like this:
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$avg = array_sum($arr) / count($arr);
$callback = function($val){ return $val < $avg };
return array_filter($arr, $callback);
这真的可能吗?在匿名函数之外计算一个变量并在内部使用它?
Is this actually possible? Calculating a variable outside of the anonymous function and using it inside?
您可以使用 use
关键字从父作用域继承变量.在您的示例中,您可以执行以下操作:
You can use the use
keyword to inherit variables from the parent scope. In your example, you could do the following:
$callback = function($val) use ($avg) { return $val < $avg; };
有关详细信息,请参阅有关匿名函数的手册页.
For more information, see the manual page on anonymous functions.
如果您运行的是 PHP 7.4 或更高版本,箭头函数 可以使用.箭头函数是另一种定义匿名函数的更简洁的方法,它自动捕获外部变量,无需use
:
If you're running PHP 7.4 or later, arrow functions can be used. Arrow functions are an alternative, more concise way of defining anonymous functions, which automatically capture outside variables, eliminating the need for use
:
$callback = fn($val) => $val < $avg;
鉴于箭头函数是多么简洁,您可以合理地直接在 array_filter
调用中编写它们:
Given how concise arrow functions are, you can reasonably write them directly within the array_filter
call:
return array_filter($arr, fn($val) => $val < $avg);