How can I include a variable inside a callback function?

烂漫一生 提交于 2020-01-03 22:26:54

问题


I'm trying to get counts of array values greater than n.

I'm using array_reduce() like so:

$arr = range(1,10);
echo array_reduce($arr, function ($a, $b) { return ($b > 5) ? ++$a : $a; });

This prints the number of elements in the array greater than the hard-coded 5 just fine.

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; });
//                                    ^                  ^

And even

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?


回答1:


The syntax to capture parent values can be found in the function .. use documentation under "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).

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;
});

Where $n is "used" from the outer lexical scope.

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.



来源:https://stackoverflow.com/questions/25181798/how-can-i-include-a-variable-inside-a-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!