Simple Usage Example of PHP Callback Function

  • 2021-12-09 08:30:41
  • OfStack

This article illustrates the simple usage of PHP callback function. Share it for your reference, as follows:

Two built-in callback functions are provided in php call_user_func() , call_user_func_array() .

The difference between these two functions is:

call_user_func_array (callable $callback, array $param_arr) accepts callback functions and arguments as an array.

call_user_func ($callback, Argument 1, Argument 2) The number of arguments is determined by the callback function.

Here are some examples of common callback functions:


// Ordinary function 
function f1($param1,$param2)
{
 echo ' Function '.__FUNCTION__.' Be executed , The parameter passed in is :'.$param1.' '.$param2;
 echo "<br/>";
}
// Pass call_user_func Call function f1
call_user_func('f1','han','wen');
// Pass call_user_func_array Call function 
call_user_func_array('f1',array('han','wen'));

Run results:

The function f1 is executed, and the parameter passed in is han wen
The function f1 is executed, and the parameter passed in is han wen


class A{
 public $name;
 function show($param)
 {
  echo ' The passed-in parameter is :'.$param."<br/>";
  echo 'my name is:'.$this->name;
  echo "<br/>";
 }
 function show1($param1,$param2)
 {
  echo __METHOD__.' Method is executed , The passed-in parameter is :'.$param1.' '.$param2."<br/>";
 }
 public static function show2($param1,$param2)
 {
  echo __METHOD__.' Method is executed , The passed-in parameter is :'.$param1.' '.$param2."<br/>";
 }
}
// Calls a non-static member function of the class, which has a $this Called a member in an object 
$a = new A;
$a->name = 'wen';
call_user_func_array(array($a,'show',),array('han!'));
// Call a non-static member function of the class, no object is created, and the member function cannot have $this
call_user_func_array(array('A','show1',),array('han!','wen'));
// Calling static member functions in a class 
call_user_func_array(array('A','show2'),array('param1','param2'));

Run results:

The parameter passed in is: han!
my name is:wen
The A:: show1 method is executed with the passed-in parameter: han! wen
The A:: show2 method is executed with the passed-in parameter: param1 param2

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of Common Functions and Skills of php", "Summary of Usage of php String (string)", "Encyclopedia of Operation Skills of PHP Array (Array)", "Tutorial on Data Structure and Algorithms of PHP" and "Summary of Programming Algorithms of php"

I hope this article is helpful to everyone's PHP programming.


Related articles: