Callback function can be used with anonymous functions and variable functions to achieve a more beautiful and complex function structure.
The callback function means that when processing a function, I want to make this function more customizable. When I allow this function to be called, I can also pass in a function to match. , assist in processing.
This is a chapter that combines variable functions and callback functions.
<?php
function woziji($one,$two,$func){
//我规定:检查$func是否是函数,如果不是函数停止执行本段代码,返回false
if(!is_callable($func)){
return false;
}
//我把$one、$two相加,再把$one和$two传入$func这个函数中处理一次
//$func是一个变量函数,参见变量函数这一章
echo $one + $two + $func($one,$two);
}
//我们定义几个函数试试
function plusx2( $foo , $bar){
$result = ($foo+$bar)*2;
return $result;
}
function jian( $x , $y ){
$result = $x - $y;
return $result;
}
//调用一下函数,woziji,向里面传入参数试试
echo woziji(20,10,'plusx2');
//将plusx2改成jian试试结果
echo woziji(20,10,'jian');
?>The processing process is as follows:
1. Assign 20 to the formal parameter $one, 10 to $two, and the two variable functions plusx2 or jian are assigned to $func
2. In the woziji function, determine whether plusx2 or jian is a function. If not, return false and stop execution.
3. Show that plusx2 or jian is a function. Therefore, $one = 20, $two =10 are added. After the addition, $one and $two are brought into $func($one,$two).
4. After bringing it in, $func is variable and can be plusx2 or jian. If it is plusx2, the two results of $one = 20, $two = 10 are given to $foo and $bar
in the plusx2 function 5.$foo + $bar multiplies the result by 2 Return to the calculation point of the function body of woziji: $one + $two + $func($one,$two);
6. In this way, we get the calculation result
Now we understand Callback function: In a callback, pass in a function name and add () brackets to the function name. Recognize it as a variable function and execute it together.
Next Section