Lambda vs Anonymous Function in PHP

In PHP, both lambda functions and anonymous functions serve similar purposes. They allow us to create functions without giving them a specific name. However, there are some differences between the two.

Syntax

Lambda functions are defined using the fn keyword, introduced in PHP 7.4:

$lambda = fn($arg1, $arg2) => $arg1 + $arg2;

Anonymous functions are defined using the function keyword:

$anonymous = function($arg1, $arg2) {
    return $arg1 + $arg2;
};

Use Cases

Lambda functions are generally more concise and are often used for simple, one-liner operations.

Anonymous functions offer more flexibility and can have multiple statements and even contain named functions and classes within them.

Variables Scope

In a lambda function, variables from the surrounding scope are automatically captured, meaning they can be used inside the lambda without any extra effort.

$x = 10;
$lambda = fn($y) => $x + $y;

In an anonymous function, you need to use the use keyword to import variables from the surrounding scope.

$x = 10;
$anonymous = function($y) use ($x) {
    return $x + $y;
};

Return Statement

Lambda functions can implicitly return the result of the expression without the need for a return statement.

Anonymous functions require a return statement to return a value explicitly.

Availability

Lambda functions were introduced in PHP 7.4, so they are only available in PHP 7.4 and later.

Anonymous functions have been available in PHP since version 5.3, making them more widely supported in older PHP versions.

In summary, lambda functions are a more concise and modern way to create simple anonymous functions in PHP, while anonymous functions provide more flexibility and are available in older PHP versions. Your choice between them should depend on your specific use case and the PHP version you are working with.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.