Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you know what parameters/arguments to put in a closure?

When do closures have parameters (or how do closures with parameters work)? I know that use() is used to import variables outside the anonymous function, but what about the parameter(s) of the closure itself?

like image 847
Jürgen Paul Avatar asked Jan 17 '23 11:01

Jürgen Paul


2 Answers

An example of closures with parameters is currying:

function greeter($greeting)
{
  return function($whom) use ($greeting) {
    // greeting is the closed over variable
    return "$greeting $whom";
  };
}

$hello_greeter = greeter('hello');

echo $hello_greeter('world'); // will print 'hello world';

The greeter function will return a "half-implemented" function that will always start with the same greeting, followed by whatever is passed into it (e.g. the person to greet).

like image 149
Ja͢ck Avatar answered Jan 31 '23 00:01

Ja͢ck


If you are using a function that accept an anonymous function as parameter, then check the doc of the function.

If the function is written by you, then you are the controller, you decide it.

like image 36
xdazz Avatar answered Jan 30 '23 23:01

xdazz