Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 200
Breno Gazzola Avatar asked Jan 03 '11 21:01

Breno Gazzola


People also ask

How do you get the variable from a callback function?

You can pass the exec function a callback. When the exec function determines the username, you invoke the callback with the username. var child = exec(cmd, function(error, stdout, stderr, callback) { var username = stdout. replace('\r\n',''); callback( username ); });

How callback function is different from normal function in Javascript?

The main difference between a normal function and a callback function can be summarized as follows: A normal function is called directly, while a callback function is initially only defined. The function is only called and executed once a specific event has occurred.

What is a callback parameter?

Any function that is passed as an argument is called a callback function. a callback function is a function that is passed to another function (let's call this other function otherFunction ) as a parameter, and the callback function is called (or executed) inside the otherFunction .

What is callback parameter in Python?

A callback is a function that is passed as an argument to other function. This other function is expected to call this callback function in its definition. The point at which other function calls our callback function depends on the requirement and nature of other function.


1 Answers

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); 
like image 117
mfonda Avatar answered Oct 13 '22 00:10

mfonda