An anonymous function in PHP is a function without a name, typically assigned to a variable or passed as an argument to another function.

- Callbacks: Pass anonymous functions to functions such as array_map().
- Variable Capture: Access variables from the surrounding scope using the use keyword.
- Closures: Create functions that retain access to captured variables.
- Flexible Code: Use anonymous functions for short, specific operations without defining named functions.
Define an Anonymous Function in PHP
Use the function keyword to define an anonymous function and assign it to a variable.
<?php
$add = function($a, $b) {
return $a + $b;
};
echo $add(10, 20);
?>
- $add stores the anonymous function.
- $a and $b are parameters that receive arguments.
- return sends the result back to the caller.
- The semicolon after the closing brace is required when assigning the function to a variable.
Use Anonymous Functions as Callbacks
Anonymous functions can be passed directly to other functions as callbacks. For example, array_map() applies a callback to each element of an array.
<?php
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(function($n) {
return $n ** 2;
}, $numbers);
print_r($squared);
?>
- The anonymous function squares each number.
- array_map() applies the callback to every element.
- The resulting array contains the squared values.
Capture Variables Using use
Anonymous functions do not automatically inherit ordinary variables from the surrounding scope. Use the use keyword to capture them.
<?php
$multiplier = 2;
$double = function($number) use ($multiplier) {
return $number * $multiplier;
};
echo $double(5);
?>
- use ($multiplier) captures the variable by value.
- The function uses the captured value when calculating the result.
- Changes to $multiplier outside the function after capture do not change the captured value.
Capture Variables by Reference
Use & inside the use clause to capture a variable by reference. Changes to the original variable are then visible inside the function.
<?php
$message = "Hello";
$greeting = function() use (&$message) {
echo $message;
};
$message = "Hi";
$greeting();
?>
- use (&$message) captures the variable by reference.
- The function accesses the current value of $message.
- Updating $message outside the function affects what the function sees.
Benefits
- Concise Code: Define small functions where they are needed.
- Callbacks: Pass functions as arguments to other functions.
- Variable Capture: Access surrounding variables using use.
- Flexibility: Create one-off operations without declaring named functions.
Limitations
- Readability: Complex anonymous functions can make code harder to understand.
- Debugging: Nested or lengthy callbacks can make errors harder to trace.
- Maintainability: Reusing complex logic may be clearer with a named function or class method.