PHP custom function callback function
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){ //我規(guī)定:檢查$func是否是函數(shù),如果不是函數(shù)停止執(zhí)行本段代碼,返回false if(!is_callable($func)){ return false; } //我把$one、$two相加,再把$one和$two傳入$func這個函數(shù)中處理一次 //$func是一個變量函數(shù),參見變量函數(shù)這一章 echo $one + $two + $func($one,$two); } //我們定義幾個函數(shù)試試 function plusx2( $foo , $bar){ $result = ($foo+$bar)*2; return $result; } function jian( $x , $y ){ $result = $x - $y; return $result; } //調(diào)用一下函數(shù),woziji,向里面?zhèn)魅雲(yún)?shù)試試 echo woziji(20,10,'plusx2'); //將plusx2改成jian試試結(jié)果 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.