In PHP, a closure is an anonymous function that can access variables outside of its own scope. It "closes" over those variables and retains their values even if they are no longer in scope. This allows closures to have a persistent state and provides a way to create more flexible and powerful functions.
Examples:
Multiple closures from one function:
//...
function createMultiplier($factor) {
return function($number) use ($factor) {
return $number * $factor;
};
}
$double = createMultiplier(2);
echo $double(5); // Output: 10
$triple = createMultiplier(3);
echo $triple(5); // Output: 15
//...
In this example, the createMultiplier()
function returns a closure that multiplies a given number by the specified factor. The closure "closes" over the $factor variable from the parent scope using the use keyword. This allows the closure to access and retain the value of $factor even after createMultiplier()
has finished executing.
We can create multiple closures using the createMultiplier()
function. Each closure will have its own persistent state based on the value of $factor
provided during its creation.
In the code above, we create two closures: $double
and $triple
. The first closure, $double
, multiplies a number by 2, and the second closure, $triple
, multiplies a number by 3. When we invoke each closure with the number 5, we get the expected results of 10 and 15, respectively.
Array manipulation with array_map()
$numbers = [1, 2, 3, 4, 5];
$multiplied = array_map(function($number) {
return $number * 2;
}, $numbers);
print_r($multiplied);
In this example, the closure is used as a callback function for array_map()
. It multiplies each element of the $numbers
array by 2 and returns a new array $multiplied
with the transformed values.
Sorting with usort()
$fruits = ['apple', 'orange', 'banana', 'grape'];
usort($fruits, function($a, $b) {
return strcmp($a, $b);
});
print_r($fruits);
Here, the closure is used as a comparison callback for the usort()
function. It sorts the $fruits array alphabetically using the strcmp()
function to compare the elements.
Event handling with addEventListener()
$button = new Button();
$button->addEventListener('click', function() {
echo 'Button clicked!';
});
$button->click();
In this example, we have a Button class with an addEventListener()
method. The closure is used as the callback to be executed when the button is clicked. When the click()
method is called, it triggers the callback, resulting in the message "Button clicked!" being echoed.
Closures are commonly used in PHP for various purposes, such as event handling, callback functions, and encapsulating functionality within a defined context. They provide a powerful way to create reusable and stateful functions in PHP.