How can I include a variable inside a callback fun

2019-07-01 09:41发布

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条回答
倾城 Initia
2楼-- · 2019-07-01 10:28

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.

查看更多
登录 后发表回答