php - 如何在回调函数中包含变量?

标签 php count callback scope array-reduce

我正在尝试获取大于 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/

相关文章:

php - 我的 MySQL 函数在乘以小数时完全失去了数学精度。这是为什么?

php - 使用阈值查找相似的十六进制颜色

sql - 计数除法在完整代码中不起作用

javascript - JS回调函数问题?

javascript - 匿名回调函数抛出错误,使得像forEach一样遍历数组

php - 表单数据未提交到MySql数据库中

php - 如何按名称列出两个连接表信息(一些有名称,一些可能为空)

r - 计算比当前数字低常数的数字

sql - 用 mysql group by 返回计数 0

java - 在JavaFX中从mysql数据库添加动态数据时回调有什么用