Home > Article > Backend Development > How to create anonymous function of PHP function?
Anonymous functions (closures) allow functions to be defined without declaring a named function, for temporary or callback functions. Syntax: $anon_func = function (parameter list) {function body}; accepts parameters and returns a value. The function body is enclosed in brackets {}. For example: filter even numbers: $anon_func = function($num) { return $num % 2 == 0;}; $even_numbers = array_filter($numbers, $anon_func);
Creation of PHP anonymous functions
Anonymous functions are also called closures, which allow functions to be defined without declaring a named function. Anonymous functions are typically used when a temporary function or callback function is required.
Syntax
The syntax of anonymous functions in PHP is as follows:
$anon_func = function (参数列表) { // 函数体 };
Parameters and return values
Just like normal functions, anonymous functions can accept parameters and return a value. The function body is enclosed in brackets {}.
Practical case
The following is an example of using an anonymous function to filter an array:
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $even_numbers = array_filter($numbers, function($num) { return $num % 2 == 0; }); print_r($even_numbers); // 输出:[2, 4, 6, 8, 10]
In this example, we create an anonymous Function that takes a number $num and returns a Boolean value indicating whether the number is even. The array_filter() function then uses this anonymous function to filter the array $numbers, retaining only elements that meet the function's conditions.
The above is the detailed content of How to create anonymous function of PHP function?. For more information, please follow other related articles on the PHP Chinese website!