A callback function refers to the invocation of a function by passing another function as a parameter to the called function, rather than passing a normal variable as a parameter
The callback function is used to pass a defined function to the inside of the function
Methods for declaring callback functions
variable function declaration
<?phpfunction Calculate ($num) {for ($i =0; $i <=10; $i + +) {if ($num ($i)) {continue;} echo $i. " nbsp ";}} function number_1 ($a) {return $a%2 = = 0;//printing cannot be divisible by 2}function number_2 ($b) {return $b >=6;//print fewer than 6}calculate (" Number_1 "); echo" <br> "; Calculate ("number_2");? >
Execution results
Call_user_func_array () function
The function requires two parameters.
The first parameter is the name of the function to invoke, and the second argument is the array type, which is the argument list.
The argument list has the same number of arguments as the function to be called
<?phpfunction Speak ($a, $b) {echo "He can Speak". $a; echo "<br>"; echo "She can Speak". $b;} function Speak_test () {return Call_user_func_array (' Speak ', Array (' Chinese ', ' 中文版 '));} Speak_test ()?>
Execution results
Class static functions and objects
The method callback function also needs to use the Call_user_func_array () function
<?phpclass speaking{static function Speak ($a, $b) {echo "He can Speak". $a, echo "<br>"; echo "She can Speak". $b; Ech O "<br>";}} Class Writting{function write ($a, $b) {echo "He can write". $a; echo "<br>"; echo "She can write". $b;}} Call_user_func_array ("Speaking", "Speak"), Array ("Chinese", "中文版"), Call_user_func_array (Array (new Writting (), ' Write '), Array ("German", "Portuguese")); >
The method in the class is static and the callback method is
Call_user_func_array (Array ("Class name", "static method in Class"))
The method in the class is not static and the callback method is
Call_user_func_array (Array (object reference, method name in object))
Execution results
·
php function (v)-callback function