Anonymous functions a.k.a closures
What are anonymous functions and how to use them?
What are anonymous functions? permalink
php.net description for anonymous functions:
Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses.
Let's consider case (like case on Stack Overflow) where you are looping over array of emails and send message to every email.
Code which won't work:
foreach ($emails as $email) {
Mail::send(function ($message) {
$message->to($email)->subject('My subject');
});
}
For clarity: $emails
is array
of email addresses. Mail::send
takes callable as argument and provides that callable with $message
which can be used to set "to" address, subject, body etc. Their logic is unimportant for this example.
Now this callable is what is anonymous function a.k.a closure. Running this code would give you a notice:
Notice: Undefined variable: email
This is because anonymous functions have their own scope and therefore are unaware of outside variables. You have to explicitly provide anonymous functions with variables from outside scope using use
language construct.
Working code:
foreach ($emails as $email) {
Mail::send(function ($message) use ($email) {
$message->to($email)->subject('My subject');
});
}
Reusing anonymous functions permalink
There may be case where you would want to reuse anonymous function. You can assign it to variable and call them by variable name.
For example, let's have an anonymous function which multiplies two numbers. Yes, it would be easier to just multiply them, but this is just for simple example :)
$multiply = function ($first, $second) {
return $first * $second;
};
echo $multiply(2, 3); // 6
echo $multiply(2, 4); // 8
This post is based on my answer on Stack Overflow. If this helped you, consider upvoting it.