PHP Closure vs Anonymous Function with Example

In PHP, both closures and anonymous functions allow you to create and use functions without having to give them a specific name. They are similar in many ways but have some differences in terms of syntax and usage. Let's explore closures and anonymous functions with examples.

Table of Contents

  1. Anonymous Function
  2. Closure
  3. Differences

Anonymous Function

An anonymous function, also known as a lambda function, is a function without a specific name. You can create an anonymous function using the function keyword. Here is an example:

$add = function ($a, $b) {
    return $a + $b;
};

$result = $add(3, 4); // Calling the anonymous function
echo $result; // Output: 7

In this example, we define an anonymous function that takes two arguments and returns their sum. We then assign this function to the variable $add and call it just like a regular function.

Closure

A closure is a special type of anonymous function that can capture and remember the values of variables from the surrounding scope. This means that closures can access variables that are not passed as arguments explicitly. Here's an example:

$base = 10;

$closure = function ($x) use ($base) {
    return $x + $base;
};

$result = $closure(5);
echo $result; // Output: 15

In this example, we define a closure that takes one argument $x and uses the $base variable from the outer scope. The use ($base) syntax is used to capture the $base variable within the closure.

Differences

  1. Scope: Closures can capture variables from their surrounding scope using the use keyword, while anonymous functions cannot.
  2. Assignment: Closures are often used when you need to create functions that have access to specific variables. Anonymous functions are more general-purpose and do not necessarily need to capture variables from the surrounding scope.
  3. Readability: Closures can sometimes make code more readable when you need to create functions that use external variables. Anonymous functions can be used for shorter, simple tasks.

In summary, both closures and anonymous functions are valuable tools in PHP for creating functions without explicitly naming them. Closures, in particular, are useful when you need to capture variables from the surrounding scope, while anonymous functions are more general-purpose. Choose the one that best fits your specific use case.


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.