Home > Article > Backend Development > How do PHP anonymous functions receive parameters?
PHP The syntax for anonymous functions to receive parameters is: function($argument1, $argument2, ..., $argumentN) { // Function body}. Arguments are passed by value or by reference (using the & symbol) and are accessed through the closure's function body.
#How do PHP anonymous functions receive parameters?
Anonymous functions, also known as closures, are advanced features in PHP that allow the creation of functions at runtime. They do not require predefined names and can be passed and receive arguments just like regular functions.
Syntax for receiving parameters
The syntax of anonymous functions is as follows:
function($argument1, $argument2, ..., $argumentN) { // 函数体 }
Parameter passing
Like Like regular functions, parameters can be passed to anonymous functions by value or reference. Pass parameters by reference using the &
notation.
// 按值传递 $increment = function($number) { return $number + 1; }; // 按引用传递 $double = function(&$number) { $number *= 2; };
Practical case
Example 1: Find elements that meet the conditions in the array
$numbers = array(1, 2, 3, 4, 5); $evenNumbers = array_filter($numbers, function($number) { return $number % 2 == 0; });
Example 2: Calculate the length of a string
$string = "Hello, world!"; $stringLength = strlen($string, function($character) { return ord($character) != 32; });
Conclusion
PHP anonymous functions provide a convenient way to receive parameters and create functions at runtime. The flexibility of passing parameters by value or reference allows them to perform well in a variety of scenarios.
The above is the detailed content of How do PHP anonymous functions receive parameters?. For more information, please follow other related articles on the PHP Chinese website!