php 使用外部计算的变量的回调函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4588714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Callback function using variables calculated outside of it
提问by Breno Gazzola
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?
这真的可能吗?在匿名函数外部计算变量并在内部使用它?
回答by mfonda
You can use the use
keyword to inherit variables from the parent scope. In your example, you could do the following:
您可以使用use
关键字从父作用域继承变量。在您的示例中,您可以执行以下操作:
$callback = function($val) use ($avg) { return $val < $avg; };
For more information, see the manual page on anonymous functions.
有关更多信息,请参阅匿名函数的手册页。
回答by Viper_Sb
use global variables i.e $GLOBAL['avg']
使用全局变量,即 $GLOBAL['avg']
$arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
$GLOBALS['avg'] = array_sum($arr) / count($arr);
$callback = function($val){ return $val < $GLOBALS['avg'] };
$return array_filter($arr, $callback);