Home >Backend Development >PHP Tutorial >The Actual Difference Between Lambda and Regular Functions (Using PHP)

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

Susan Sarandon
Susan SarandonOriginal
2025-01-30 00:22:09262browse

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

The problem of the context of the function

When we pass the function as a parameter, if we need to use a variable outside the function, we must use

keywords.

use This is common in the group route of Laravel or Lumen.

Please note that The use of keywords is necessary: ​​

use The above code is taken from Lumen's document. If the Lambda function (arrow function) is used to rewrite this code, all other variables outside the function can be used inside the function.

<code class="language-php">$router->group(['prefix' => 'admin'], function() use ($router) {
    $router->get('users', function() {
        // 匹配 "/admin/users" URL
    });
});</code>
Rewriting the lambda function

Please note that here you don't need to use keyword

, the code is more concise.

use This is one of the most important features of the lambda function. It enables the Lambda function to create a closure (the closure is not within the scope of the discussion in this article) and many other functional programming concepts.

Other situations
<code class="language-php">$router->group(['prefix' => 'admin'], fn() => (
    $router->get('users', fn() => (
        // 匹配 "/admin/users" URL
    ));
));</code>

In other languages, there is no

keyword, and the function does not know the context around it. In this case, how to achieve similar behavior?

You need to pass the variables as parameters every time, but this is really not what we want. use

The above is the detailed content of The Actual Difference Between Lambda and Regular Functions (Using PHP). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn