Callback function using variables calculated outside of it

后端 未结 2 1693
一向
一向 2020-12-08 18:46

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){ retu         


        
相关标签:
2条回答
  • 2020-12-08 18:53

    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.

    0 讨论(0)
  • 2020-12-08 19:03

    use global variables i.e $GLOBAL['avg']

    $arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    $GLOBALS['avg'] = array_sum($arr) / count($arr);
    $callback = function($val){ return $val < $GLOBALS['avg'] };
    
    $return array_filter($arr, $callback);
    
    0 讨论(0)
提交回复
热议问题