Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

php - Callback function using variables calculated outside of it

Basically I'd like to do something like this:

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$avg = array_sum($arr) / count($arr);
$callback = function($val){ return $val < $avg };

return array_filter($arr, $callback);

Is this actually possible? Calculating a variable outside of the anonymous function and using it inside?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the use keyword to inherit variables from the parent scope. In your example, you could do the following:

$callback = function($val) use ($avg) { return $val < $avg; };

For more information, see the manual page on anonymous functions.

If you're running PHP 7.4 or later, arrow functions can be used. Arrow functions are an alternative, more concise way of defining anonymous functions, which automatically capture outside variables, eliminating the need for use:

$callback = fn($val) => $val < $avg;

Given how concise arrow functions are, you can reasonably write them directly within the array_filter call:

return array_filter($arr, fn($val) => $val < $avg);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...