Anonymous Function in PHP
When you define a function in PHP, you give it a name, which allows you to be called later by referencing this name. However, PHP also supports anonymous function like other programming languages.
An anonymous function, also known as closure, is a function in PHP that does not have a specified name following the function keyword. It is an important feature of many modern programming languages and was introduced in PHP 5.3 version.
The general syntax to define an anonymous function in PHP is as follows:
$variableName = function($parameter_list) {
// Function body
};
In the above syntax of anonymous function, the anonymous function is often assigned to a variable and then called through that variable. You can also pass as an argument to another function, or even returned as the output of another function.
Basic Examples based on Anonymous Function in PHP
Example 1:
<?php
$greet = function($name) {
return "Welcome, $name!";
};
echo $greet("Saanvika"); // Calling the function.
?>
Output: Welcome, Saanvika!
In this example, we have defined an anonymous function that takes one formal parameter, $name and returns a string value. We have assigned the anonymous function to a variable named $greet. Next, we have called the function by passing an argument to the parameter of the function.
Example 2: Let’s write a PHP program to square of a number using anonymous function.
<?php
$square = function($number) {
return $number * $number;
};
echo "Square of 25 = ". $square(25);
?>
Output: Square of 25 = 625
Example 3:
<?php
$cube = function($number) {
$cb = $number * $number * $number;
echo $cb;
};
$cube(5);
?>
Output: 625
Passing Anonymous Functions as Arguments
You can also pass an anonymous function to another PHP function and execute within it. Here is a very simple program to exhibit passing an anonymous function as an argument:
Example 4:
<?php
function executeCallback($callback) {
// Pass an argument value 5 to the anonymous function.
$result = $callback(5);
echo "Result: $result\n";
}
// Call the regular function and pass an anonymous function as an argument.
executeCallback(function($number) {
return $number * 3;
});
?>
Output: Result: 15
In this example, we have defined a named function called executeCallback() that takes one formal parameter named $callback. This parameter $callback acts as a callable function. In this code, the callable is an anonymous function (also known as a closure) passed to executeCallback() function.
A callable in PHP refers to anything that can be called as a function, such as:
- Named functions
- Anonymous functions (closures)
- Object methods or static methods
Inside the executeCallback(), the $callback is called like a regular function by passing the value 5 as an argument. This triggers the anonymous function with $number = 5. We have stored the result of the $callback function execution in the variable $result and the echo statement prints the result.
Next, an anonymous function is passed directly as an argument to parameter $callback of the executeCallback() function. It takes a single parameter $number, multiplies $number by 3, and returns the result. The result is returned from the anonymous function to executeCallback() function.
Example 5:
<?php
function processArray($array, $callback) {
// Iterating array elements using foreach loop.
foreach ($array as $item) {
echo $callback($item) . "\n";
}
}
// Declare an array.
$numbers = [1, 2, 3, 4, 5];
// Calling the regular function by passing arguments array and anonymous function().
processArray($numbers, function($number) {
return $number * $number;
});
?>
Output: 1 4 9 16 25
Closures: Accessing Variables Outside Anonymous Function
PHP allows to access variables from the outer scope inside anonymous function using the use keyword. This important feature is called closures in PHP. Let’s take a simple example on it.
Example 6:
<?php
$message = "Welcome to Scientech Easy!";
// Accessing outer scope variable using use keyword in the anonymous function.
$greet = function($name) use ($message) {
return "$message, $name!";
};
echo $greet("Alice");
?>
Output: Welcome to Scientech Easy!, Alice!
In this example, we have accessed the variable $message from the outer scope using the use keyword inside the anonymous function.
Practical Use Cases of Anonymous Functions
Let’s take some practical cases where we commonly use an anonymous function as an argument in PHP.
Example 7: Sorting array
<?php
// Creates an array of numbers.
$numbers = [3, 1, 4, 1, 5, 9, 12, 0];
// Calling usort() function to sort an array.
usort($numbers, function($a, $b) {
return $a <=> $b;
});
// Display the sorted array.
print_r($numbers);
?>
Output: Array ( [0] => 0 [1] => 1 [2] => 1 [3] => 3 [4] => 4 [5] => 5 [6] => 9 [7] => 12 )
In this example, we have sorted an array using an anonymous function as a custom comparator. First, we have created an array of numbers and stored them in a variable named $numbers. Then, we have used the usort() function to sort the array. This method takes two arguments:
- The array to be sorted ($numbers).
- A callback function to define the custom sorting logic.
Here, the callback function is an anonymous function. The anonymous function takes two parameters, $a and $b, which represent elements of the array being compared during sorting.
Inside the anonymous function, we have the spaceship operator (<=>) to compare $a and $b. It returns:
- -1 if $a is less than $b.
- 0 if $a is equal to $b.
- 1 if $a is greater than $b.
The usort() function provided by an array uses the return value of the comparator (i.e. anonymous) function to determine the order of array elements:
- If -1 is returned, $a comes before $b.
- If 1 is returned, $a comes after $b.
- If 0 is returned, the order remains unchanged.
Example 8: Event listener
<?php
$event = function() {
echo "Event triggered!";
};
$event();
?>
Output: Event triggered!
The most common uses of anonymous function is as an argument to array functions like array_map() and array_filter(). Let’s take examples on it.
Example 9: Use in array_map() function
<?php
// Creating an array.
$numbers = [1, 4, 3, 4, 5, 6];
// Declare anonymous function.
$squareNum = function($number) {
return $number * $number;
};
// Calling the array_map() function.
$squaredNumbers = array_map($squareNum, $numbers);
print_r($squaredNumbers);
?>
Output: Array ( [0] => 1 [1] => 16 [2] => 9 [3] => 16 [4] => 25 [5] => 36 )
Example 10: Use in array_filter() function
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14];
$evenNumbers = array_filter($numbers, function($number) {
return $number % 2 === 0;
});
print_r($evenNumbers);
?>
Output: Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 [10] => 12 [11] => 14 )
In this example, we have used an anonymous function to filter even numbers from an array.
Quiz and Exercise
Question 1: What will be the following code output?
<?php
$message = "Hello";
$greet = function($name) use ($message) {
return "$message, $name!";
};
$message = "Hi";
echo $greet("John");
?>
Options:
- A) Hi, John!
- B) Hello, John!
- C) Undefined variable: message
- D) Error
Answer: B) Hello, John!