Search code examples
phplaravelscopelumen

What does the line "function () use ($app) {" means in the Lumen docs (probably valid in Laravel)


I've seen the function () use ($app) { syntax done over and over again in the Lumen docs here.

The full syntax looks like that:

$app->group(['middleware' => 'auth'], function () use ($app) {
    $app->get('/', function ()    {
        // Uses Auth Middleware
    });
});

Is this thing somehow related to the PHP? Lumen? Is it also available in the Laravel?

It looks like the anonymous function in PHP without the curly brackets, however, the use keyword doesn't make sense in the context of this particular code example. As far as I know, using use could be like an alias or the trait in the context of OOP.

Tried changing it a little bit, because I'm not a huge fan of the function () :D My attempt using function () { use ($app) { results in the syntax error.

I haven't seen anything like that in the PHP before, could you give me some details about it?


Solution

  • When in a closure function (any function which closes over the environment in which it was defined), you need to make use of an external variable you use the use ($foo, $var, ...) to make them available inside the function.

    For example, the next closure function would throw an exception:

        $name = 'Mark';
    
        \DB::table('users')
            ->where(function ($query) {
                $query->where('email', 'some_email')
                    ->orWhere('name', $name) // <- $username doesn't exist here
            });
    

    because $name is not defined inside the closure function.

    That's when use comes in handy:

        $name = 'Mark';
    
        \DB::table('users')
            ->where(function ($query) use ($name){
                $query->where('email', 'some_email')
                    ->orWhere('name', $name) // <- now it's available
            });
    

    Returning to your original question, that isn't exclusive to Lumen, I've just checked and it is also present in Laravel apps (same family, so not a surprise). I think that the $app represents the Lumen/Laravel's Service Container (read this for more info: Understanding the Laravel Service Container) and that is needed in this case to register routes and make them available everywhere (inside the app).