Home >Backend Development >PHP Tutorial >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>
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.
<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!