Callback and anonymous functions in PHP, and anonymous php callback Functions
Preface
Some time ago, I became a dog in my company. I felt my head deep when I went home from work every day. There are also various things on Saturday and Sunday. If you don't want to get started with the code, your blog will be dragged down. I don't expect to be too busy recently. I am free to write it. I 'd like to summarize and share some of my gains. Please pay attention to it.
Callback and anonymous Functions
Callback functions and closures are no stranger to JS. JS uses them to complete the event mechanism and perform many complex operations. PHP is not often used. Let's talk about callback and anonymous functions in PHP today.
Callback Function
Callback Function: Callback (that is, the main function is returned after the main function calls the operation), refers to the reference of a piece of executable code that is passed to other code through function parameters.
The common explanation is to pass a function as a parameter into another function. PHP has many "function requiring parameters as functions", such as array_map, usort, and call_user_func_array, they execute the passed functions and then directly return the results to the main function. The advantage is that functions are easy to use as values, and the code is concise and readable.
Anonymous functions:
Anonymous functions, as the name implies, do not have a function that determines the function name. PHP regards anonymous functions and closures as the same concept (anonymous functions are also called closure functions in PHP ). Of course, it can only be used as a variable.
PHP assigns a function to a variable in four ways:
- We often use: functions are built into external definitions/or PHP, and function names are directly passed in as string parameters. NOTE: If it is a CLASS static function, it is passed in CLASS: FUNC_NAME.
- Use
create_function($args, $func_code);
Create a function. A function name is returned. $ Func_code is the code body and $ args is the parameter string separated by commas;
- Direct assignment:
$func_name = function($arg){statement};
- Directly use anonymous functions, define functions directly in parameters, and do not assign specific variable values;
The first method is generally used and will not be mentioned. The second method is similar to the eval () method, which is officially listed as not recommended by PHP, and its definition method is too intuitive, I have never used it in other places except for testing. Here we will focus on the third and fourth usage;
The last two types of functions are called anonymous functions, that is, closure functions. The third method of value assignment is flexible and can be referenced by variables. Availableis_callable($func_name)
To test whether the function can be called or through$func_name($var)
And the fourth method is similar to the callback function in JS. It is directly used without variable assignment;
The use keyword can be used to reference variables in the parent scope when defining a function. The usage isfunction($arg) use($outside_arg) {function_statement}
. $ Outside_arg is a variable in the parent scope and can be used in function_statement.
This method is used in callback functions."Quantity of parameter values determined". For example, the value of $ callback parameter required by usort is two, but we need to introduce other parameters to affect sorting. What should we do? Use the use () keyword to easily introduce a new variable into $ callback for internal use.
Array_map/array_filter/array_walk:
Put these three functions together because these three functions are similar in execution logic, similar to the following code:
$result = [];foreach($vars as $key=>$val){ $item = callback(); $result[] = $item;}return $result;
Array_walk ($ vars, $ callback)
Its callback should be as follows:
$callback = function(&$val, $key[, $arg]){ doSomething($val); }
Array_walk returns whether execution is successful, which is a Boolean value. Adding a reference symbol to $ value can change the value of $ value in the function to change the $ vars array. Because its $ callback requires two parameters, array_walk cannot Input $ callback such as strtolower/array_filter. to implement similar functions, you can use the array_map () parameter to be discussed later ().
Array_walk_recursive ($ arr, $ callback );
The returned value and execution mechanism are similar to array_walk;
Its callback is the same as that of array_walk. The difference is that if $ val is an array, the function will recursively process $ val; note that the $ key whose $ val is an array will be ignored.
Array_filter ($ vars, $ callback, $ flag );
Its $ callback is similar:
$callback = function($var){ return true or false; }
Array_filter filters out the items that are returned as false when $ callback is executed, and array_filter returns the filtered array.
The third parameter $ flag determines the value of the callback parameter $ var. However, this may be a feature of the PHP high version, which is not supported by PHP5.5.3. You can test it by yourself. The value of each item in the array is input by default. When the flag is ARRAY_FILTER_USE_KEY, the key and value of each item in the array are input;
Array_map ($ callback, & $ var_as [, $ var_bs...]);
Its $ callback is similar:
$callback = function($var_a[, $var_b...]){ doSomething($var_a, $var_b); }
Returns the $ var_as array after callback processing (the original array will be changed). If there are multiple arrays, two projects with the same sequence of arrays will be passed in for processing, the number of executions is the maximum number of projects in the parameter array;
Usort/array_reduce
Put these two functions in one, because their execution mechanisms are somewhat special.
Usort (& $ vars, $ callback)
$ Callback should be as follows:
callback = function($left, $right){ $res = compare($left, $right); return $res; }
Usort returns whether the execution is successful, bool value. User-Defined Methods Compare $ left and $ right. $ left and $ right are any two items in $ vars;
$ Left> $ right returns a positive integer, $ left <$ right returns a negative integer, and $ left = $ right returns 0;
The elements in $ vars are extracted and sorted in ascending order. To sort the returned values of $ callback in descending order, you can reverse the returned values.
Array_reduce ($ vars, $ callable [, mixed $ initial = NULL])
$ Callback should be as follows:
$callback = function($initial, $var){ $initial = calculate($initail, $var); return $initial; }
The initial value $ initial is null by default and returns the initial after iteration. You must return $ initial so that the value of $ initial can be continuously changed to achieve iteration.
Here, by the way, map and reduce are different:
Map: traverses the members in the array. Each time a processed value is returned, the final result value is composed of all processed values.Arrays;
Reduce: traverses the array members. Each time an array member is used to combine the initial value for processing, the initial value is returned. Even if the result of the previous execution is used together with the next input, the result is generated. The result value isOne item;
Call_user_func/call_user_func_arraycall_user_func [_ array] ($ callback, $ param)
$ Callback:
$callback = function($param){ $result = statement(); return $result; }
Multiple return values. For details, see $ callback.
Using this function to implement the PHP event mechanism is not very advanced. After the judgment conditions are met, or after the program executes a certain step, call_user_func () will be OK. In my previous blog, I also introduced my PHP framework (2)
Summary
In fact, the above $ callback does not need to be defined separately and variables can be referenced. The fourth function definition method mentioned above can be defined directly in the function, and the 'complete' anonymous function can be used. For example:
usort($records, function mySortFunc($arg) use ($order){ func_statement;});
Isn't it forced?
OK. Several usage instructions are introduced ~ I hope to help you. If you have any questions, please point out that if you like it, you can click here to recommend ~
The blog is continuously updated. You are welcome to pay attention to it.