如何在回调函数中包含变量? [英] How can I include a variable inside a callback function?
问题描述
我正在尝试获取大于n
的数组值.
I'm trying to get counts of array values greater than n
.
我正在像这样使用array_reduce()
:
$arr = range(1,10);
echo array_reduce($arr, function ($a, $b) { return ($b > 5) ? ++$a : $a; });
这会打印出比硬编码的5
还要大的数组中的元素数.
This prints the number of elements in the array greater than the hard-coded 5
just fine.
但是如何使5
像$n
这样的变量?
But how can I make 5
a variable like $n
?
我尝试过引入这样的第三个参数:
I've tried introducing a third argument like this:
array_reduce($arr, function ($a, $b, $n) { return ($b > $n) ? ++$a : $a; });
// ^ ^
甚至
array_reduce($arr, function ($a, $b, $n) { return ($b > $n) ? ++$a : $a; }, $n);
// ^ ^ ^
这些工作都没有.您能告诉我如何在此处添加变量吗?
None of these work. Can you tell me how I can include a variable here?
推荐答案
The syntax to capture parent values can be found in the function .. use
documentation under "Example #3 Inheriting variables from the parent scope".
..从父级作用域继承变量[需要'use'形式,并且不与使用全局变量相同..闭包的父级作用域是闭包所在的函数被声明(不一定是调用它的函数).
.. Inheriting variables from the parent scope [requires the 'use' form and] is not the same as using global variables .. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).
然后在use
的帮助下转换原始代码:
Converting the original code, with the assistance of use
, is then:
$n = 5;
array_reduce($arr, function ($a, $b) use ($n) {
return ($b > $n) ? ++$a : $a;
});
从外部词汇范围使用" $n
的地方.
Where $n
is "used" from the outer lexical scope.
注意:在上面的示例中,提供了值的副本,并且变量本身未绑定.请参阅有关使用变量引用(例如&$n
)以能够在父上下文中重新分配变量的文档.
NOTE: In the above example, a copy of the value is supplied and the variable itself is not bound. See the documentation about using a reference-to-a-variable (eg. &$n
) to be able and re-assign to variables in the parent context.
这篇关于如何在回调函数中包含变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!