我正在尝试获取大于 n
的数组值的计数。
我像这样使用 array_reduce()
:
$arr = range(1,10);
echo array_reduce($arr, function ($a, $b) { return ($b > 5) ? ++$a : $a; });
这会打印出数组中元素的数量大于硬编码的 5
就好了。
但是我怎样才能使 5
成为像 $n
这样的变量呢?
我试过像这样引入第三个论点:
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);
// ^ ^ ^
这些都不起作用。你能告诉我如何在此处包含变量吗?
最佳答案
可以在 function .. use
中找到捕获父值 的语法“Example #3 Inheriting variables from the parent scope”下的文档。
.. 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
的帮助下转换原始代码,然后是:
$n = 5;
array_reduce($arr, function ($a, $b) use ($n) {
return ($b > $n) ? ++$a : $a;
});
$n
是从外部词法范围“使用”的地方。
注意:在上面的示例中,提供了值的副本 并且变量本身未绑定(bind)。请参阅有关使用变量引用(例如 &$n
)能够并重新分配给父上下文中的变量的文档。
关于php - 如何在回调函数中包含变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25181798/