I'm pretty new to Lumen and I'm following this tutorial to learn a basic authentication with JWT through Lumen: https://medium.com/tech-tajawal/jwt-authentication-for-lumen-5-6-2376fd38d454
Now its this part of code which puts some questionmarks over my head:
$router->group(
['middleware' => 'jwt.auth'],
function() use ($router){
$router->get('users', function(){
$users=\App\User::all();
return response()->json($users);
});
}
);
I dont understand what function() use ($router)
does?
I read the official of PHP on use: https://www.php.net/manual/de/language.namespaces.importing.php
And I also looked into an external ressource:
https://www.tutorialspoint.com/php7/php7_use_statement.htm
But I guess I would still require some knowledge about the inner workings of Lumen/Laravel to understand whats happening here. Can someone please give me a lift and explain to me in a few lines whats happening here?
It is a PHP feature for bringing an outside variable into the scope of the anonymous function / Closure.
$a = 'hello';
$callback = function ($something, $else) use ($a) {
echo $a;
};
Without that use
declaration the $a
variable would not be in the scope of that function.
Since something else is executing your callback, you aren't controlling the arguments passed to it, but you can control the variables you are bringing into the scope of it.
"Closures may also inherit variables from the parent scope. Any such variables must be passed to the
use
language construct."
PHP Manual - Anonymous Functions Example #3
Additional Information:
If you look at an example of the map
function for Laravel's Collection class you will see this:
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
In this case they are showing you that your callback will have a Collection's item and key passed to it as arguments.