Home > Article > Backend Development > How to use PHP anonymous functions?
Anonymous functions, also known as closure functions, are a function type introduced in PHP 5.3 that allow functions to be defined without names. Its advantages include code simplicity, dynamic creation, and local scope. Common examples of using anonymous functions include using them with array functions such as array_filter() to implement more complex filtering logic, such as filtering arrays based on the even/odd properties of numbers.
How to use PHP anonymous functions
Anonymous functions, also known as closure functions, were introduced in PHP 5.3 A function type that allows functions to be defined without names. This is useful when you need to create functions dynamically or create locally scoped functions within a nested function.
Create anonymous functions
The syntax for creating anonymous functions is very simple:
$anonFunc = function ($args) { // 函数主体 };
For example, the following anonymous function calculates the sum of two numbers:
$sum = function ($a, $b) { return $a + $b; };
Calling anonymous functions
Calling anonymous functions is the same as calling ordinary functions:
echo $sum(10, 20); // 输出:30
Advantages of using anonymous functions
Practical case
Use array_filter() to sort the array
Anonymous functions can be used with array functions ( Such as array_filter()
) used together to implement more complex filtering logic. The following example filters an array by the even/odd properties of numbers:
$array = [1, 2, 3, 4, 5, 6, 7, 8]; $even = array_filter($array, function ($num) { return $num % 2 == 0; }); $odd = array_filter($array, function ($num) { return $num % 2 != 0; });
Now, $even
will contain all the even numbers in the array, while $odd
will contain all the odd numbers.
The above is the detailed content of How to use PHP anonymous functions?. For more information, please follow other related articles on the PHP Chinese website!