The Problem Of Function Context
When we pass a function as a parameter or something like that, and we want to use some variables from outside of the function we need to use the use
keyword.
This can be found in Laravel or Lumen in the group routing.
Notice how using the use keyword is necessary here:
$router->group(['prefix' => 'admin'], function() use ($router) {
$router->get('users', function() {
// Matches the "/admin/users" URL
});
});
The code above is from the docs of Lumen, if we would rewrite that code using the lambda functions (arrow functions) here it will have all the other variables outside of the function available in it.
Rewrite With Lambda Functions
Notice how we didn't need to have the use
keyword here and it's much cleaner.
$router->group(['prefix' => 'admin'], fn() => (
$router->get('users', fn() => (
// Matches the "/admin/users" URL
));
));
That's one of the most important parts of lambda functions, and it is what makes them able to create closures (closures are beyond the scope of this article) and many other functional concepts.
Some Other Cases
In some other languages, there's no use
keyword and functions don't have any knowledge about the context around it.
In that case, how would you have similar behavior?
You'll need to pass them as parameters each time, and we don't want that indeed.
Top comments (1)
I consider knowing the parent variables inside the function more a specific use case speciality than an important part.
In the post example there is a group method that has a callback argument, And in that callback the same object defines the actual route.
That is clunky code, and now Laravel uses another way to do the same thing.
Instead of using one instance multiple times, every definition as their way of adding the route or routes to the route collection.