PHP Anonymous Functions

In PHP, an anonymous function (also called a closure) is a function that has no name. It is often used as a callback function or stored in a variable.

🔹 Syntax of an Anonymous Function

Unlike regular functions defined using function functionName(), anonymous functions are created using function() and can be assigned to a variable.

📝 Example 1: Storing an Anonymous Function in a Variable

Here’s a simple example where an anonymous function is assigned to a variable and then executed.

<?php
// Assign an anonymous function to a variable
$greet = function($name) {
    return "Hello, $name!";
};

// Call the function
echo $greet("John");
?>

Try It Now

Explanation:

  • The anonymous function is stored in the variable $greet.
  • It is later executed like a normal function by calling $greet("John").

📝 Example 2: Using an Anonymous Function as a Callback

Anonymous functions are often used as **callback functions**, especially in array functions like array_map().

<?php
$numbers = [1, 2, 3, 4, 5];

// Using an anonymous function with array_map()
$squared = array_map(function($n) {
    return $n * $n;
}, $numbers);

print_r($squared);
?>

Try It Now

Explanation:

  • The function inside array_map() is an anonymous function.
  • It squares each element in the $numbers array.
  • The result is a new array with squared values.

📝 Example 3: Using the use Keyword in Closures

Anonymous functions cannot directly access variables outside their scope. However, you can use the use keyword to import external variables.

<?php
$message = "Hello";

// Closure using 'use' to access external variable
$greet = function($name) use ($message) {
    return "$message, $name!";
};

echo $greet("Alice");
?>

Try It Now

Explanation:

  • The variable $message is outside the function.
  • Using use ($message), we bring it into the function’s scope.

📝 Example 4: Returning an Anonymous Function

Functions can return anonymous functions, allowing dynamic function creation.

<?php
function createMultiplier($factor) {
    return function($number) use ($factor) {
        return $number * $factor;
    };
}

$double = createMultiplier(2);
echo $double(5); // Output: 10
?>

Try It Now

Explanation:

  • The function createMultiplier() returns an anonymous function.
  • The returned function uses use ($factor) to access the multiplier.
  • $double = createMultiplier(2); creates a function that doubles numbers.

🎯 Key Takeaways

  • function() creates an **anonymous function (closure)**.
  • Anonymous functions are often **stored in variables** or **used as callbacks**.
  • Use the use keyword to **import external variables** into an anonymous function.
  • Functions can **return anonymous functions**, enabling flexible and reusable code.

📝 Practice Time!

Modify these examples and experiment with **PHP anonymous functions** for a deeper understanding! 🚀