20. Anonymous Functions and Closures
Modern PHP utilizes functions that do not have a defined name. These are crucial for concepts like callbacks, filtering arrays, and passing logic as arguments.
Anonymous Functions (Lambdas)
An anonymous function is a function without a name, stored in a variable.
php
<?php // Assigning the function body to a variable $multiply $multiply = function($a, $b) { return $a * $b; }; // Calling the function using the variable name echo "5 * 4 = " . $multiply(5, 4); ?>Closures
An anonymous function becomes a closure when it imports variables from the surrounding scope (the parent scope) using the use keyword.
Note: Anonymous functions in PHP cannot automatically access local variables from the surrounding scope; they must be explicitly imported.
php
<?php $base_rate = 0.15; // Local variable in the global scope $calculate_fee = function($price) use ($base_rate) { return $price * $base_rate; }; $product_price = 200; $fee = $calculate_fee($product_price); echo "Fee for item: " . $fee; // Output: 30 // We can even change the imported variable's value by reference (&) $modifier = 5; $increment = function() use (&$modifier) { $modifier++; }; $increment(); $increment(); echo "<br>New Modifier Value: " . $modifier; // Output: 7 ?>Closures are widely used in frameworks and functions like array_map or array_filter.