PHP callback function

The callback function can be combined with anonymous functions and variable functions to implement a more elegant and complex function structure.

The callback function is to make this function more powerful when processing a function. When I call this function, I can also pass a function to cooperate and assist in processing.

This is a chapter on the combination of variable functions and callback functions.


Function woziji($one,$two,$func){
       / / I stipulate: Check if $func is a function, if not the function stops executing this code, return false
               Return false;
       //I add $one, $two, and then pass $one and $two to $func.
       //$func is a variable function, see the chapter on variable functions.
       Echo $one + $two + $func($one,$two);
} ?>

/ / We define several functions to try
Function plusx2( $foo , $bar){
       $result = ($foo+$bar)*2;
       Return $result;
Function jian( $x , $y ){
   $result = $x - $y;
   Return $result;

/ / Call the function, woziji, try to pass the parameters inside
Echo woziji(20,10,'plusx2');
/ / Change the plusx2 to jian try results
Echo woziji(20,10,'jian');
The process is like this:

    1. Assign 20 to the parameter $one, assign 10 to $two, and addx2 or jian to the variable function, assign it to $func

    2. In the woziji function to determine whether plusx2 or jian is a function, not a function, return false, stop executing

    3. Display plusx2 or jian is a function. So $one = 20, $two =10 is added, and after adding, $one and $two are brought into $func($one,$two).

    4. Bring it into the inside and $func, which is variable, can be plusx2 or jian. If it is plusx2, the two results of $one = 20 and $two = 10 give $foo and $bar to the plusx2 function.

    5.$foo + $bar Multiply by 2 to return the result to the operation of the function body of woziji: $one + $two + $func($one,$two);

    6. The master gets the result of the operation.

Now that we understand the callback function: in a key, pass in a function name, and add the () parenthesis to the function name. Recognized as a variable function, with the implementation.

Last Updated: 2018-07-06 12:32:44 By akshay


share_facebook share_twitter share_google_plus

Please Comment Here :