People familiar with node development are certainly not unfamiliar with callback functions, but they are not used in PHP. In fact, PHP also supports callback functions, today we will explain the use of the callback function in PHP and anonymous functions.
callback function
callback function: Callback (that is, call and back
The main function is returned after being called by the main function), which refers to a piece of executable code that passes through the function arguments to other code.
The popular explanation is that the function is passed into another function as a parameter, and there are many functions in PHP that require parameters as functions, like Array_map,usort,call_user_func_array, they execute the incoming function and return the result directly to the main function. The advantage is that the function is easy to use as a value, and the code is concise and readable.
Anonymous functions:
Anonymous functions, as the name implies, do not have a function to determine the name of the function, PHP will be anonymous functions and closures as the same concept (anonymous function in PHP is also called as a closure function). Its usage, of course, can only be used as a variable.
There are four ways to assign a function to a variable in PHP:
We often use: functions in the external definition/or PHP built-in, directly the function name as a string parameter passed in. Note: If it is a class static function, it is passed in Class::func_name way.
Use Create_function ($args, $func _code); Create a function that returns a function name.
$func _code as the code body, $args as a parameter string, separated by ', ';
Direct assignment: $func _name = function ($arg) {statement};
Directly use anonymous function, directly define the function at the parameter, do not assign to the concrete variable value;
The first way is usually used, no longer mentioned, the second use of the Eval () method, also by the PHP official list is not recommended to use the way, and its definition is too non-intuitive, I in addition to testing, but also not used in other places, but also omitted to mention. Here, the third and fourth usages are emphasized;
The latter two created functions are called anonymous functions, that is, the closure function, the third method of assignment created by the method is very flexible, can be referenced by a variable. You can use Is_callable ($func _name) to test whether this function can be called, or it can be called directly through $func_name ($var), whereas the fourth method creates a function that is similar to a callback function in JS and does not require a variable assignment and is used directly;
In particular, the Use keyword, which can be used when defining a function, refers to a variable in the parent scope, using the function ($arg) usage ($outside _arg) {function_statement}. Where $outside_arg is a variable in the parent scope and can be used in function_statement.
This usage is used in functions where the callback function "determines the number of parameter values". If the parameter value of Usort demand $callback is two, but we need to introduce other parameters to influence the sorting? Using the use () keyword makes it easy to introduce a new variable into the $callback internal use.
Array_map/array_filter/array_walk:
Putting these three functions together is 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 succeeds, is a Boolean value. Adding a reference symbol to a $value can change the $value value within the function to achieve the effect of changing the $vars array. Because of its $callback on the number of parameters required for two, Array_walk can not be passed strtolower/array_filter such as $callback, if you want to implement similar functions, you may use the next to say Array_map ().
Array_walk_recursive ($arr, $callback);
The return value and execution mechanism are similar to array_walk;
The callback is the same as Array_walk, but if the $val is an array, the function will handle the $val recursively, and it is important to note that $val of the array will be ignored.
Array_filter ($vars, $callback, $flag);
Its $callback is similar to:
$callback = function ($var) { return True or false; }
Array_filter filters out items returned as false when $callback executes, Array_filter returns the array after filtering is complete.
The third parameter $flag determine the value of its callback parameter $var, but this may be a PHP high version of the feature, my PHP5.5.3 do not support, you can test themselves. The default incoming array is the value of each entry, when the flag is array_filter_use_key the Key,array_filter_use_both incoming key and value for each entry in the array;
Array_map ($callback, & $var _as [, $var _bs ...];
Its $callback is similar to:
$callback = function ($var _a[, $var _b ...]) { dosomething ($var _a, $var _b);}
Returns an array of $var_as after callback processing (which changes the original array), and if there are multiple arrays, the number of items in the same order of two arrays is passed in, and the number of executions is the highest of the items in the parameter array;
Usort/array_reduce
Put these two functions together because their execution mechanism is a bit special.
Usort (& $vars, $callback)
$callback should be as follows:
callback = function ($left, $right) { $res = compare ($left, $right); return $res;}
Usort returns a bool value for execution success or not. User-defined methods compare $left and $right, where $left and $right are any two of the $vars;
Returns a positive integer $left > $right, returns a negative integer $left < $right, and returns 0 when $left = $right;
Elements in the $vars are removed and sorted in ascending order from small to large. To implement a descending arrangement, reverse the return value of the $callback.
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, defaults to NULL, returning the initial after iteration, and it is important to return the $initial so that the $initial value can be changed continuously to achieve the effect of the iteration.
Here by the way, the difference between map and reduce:
Map: Iterate through the members of the array, each time a value is returned, and the result value is a multi-item array of all processed values;
Reduce: Iterates through the array members, each time using the array member in conjunction with the initial value, and returning the initial value, that is, using the result of the last execution, with the next input to continue to produce results, the result value is one item;
Call_user_func/call_user_func_array
Call_user_func[_array] ($callback, $param)
$callback shape:
$callback = function ($param) { $result = statement (); return $result;}
Return a variety of values, specifically see $callback.
This function can be used to implement the PHP event mechanism, in fact, is not advanced, in the judgment of the condition, or the execution of the program to a certain step after call_user_func () ok. This I have in the previous blog also introduced to: build their own PHP Framework Experience (II)
Summarize
In fact, the above $callback does not have to define and use the variable reference alone, using the fourth function definition described above, directly within the function definition, using the ' full ' anonymous function on the line. Such as:
Usort ($records, function Mysortfunc ($arg) use ($order) { func_statement;});
Is it a full force?
Related reading:
Probe into the anonymous function of PHP's closure (Closure)
An explanation of PHP anonymous functions and precautions
PHP Anonymous and use clause usages, anonymous using clause instance _php tutorial