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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With