DEV Community

Abdelrahman Dwedar
Abdelrahman Dwedar

Posted on

1

The Actual Difference Between Lambda and Regular Functions (Using PHP)

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
    });
});
Enter fullscreen mode Exit fullscreen mode

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
    ));
));
Enter fullscreen mode Exit fullscreen mode

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
xwero profile image
david duymelinck

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.

Route::prefix('admin')->group(function () {
    Route::get('/users', function () {
        // code
    });
});
Enter fullscreen mode Exit fullscreen mode

Instead of using one instance multiple times, every definition as their way of adding the route or routes to the route collection.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay