Home  >  Article  >  Backend Development  >  How to create anonymous function of PHP function?

How to create anonymous function of PHP function?

WBOY
WBOYOriginal
2024-04-10 11:18:01313browse

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);

PHP 函数的匿名函数如何创建?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn