Home >Backend Development >PHP Tutorial >Analysis of call_user_func function and call_user_func_array function_PHP tutorial
Today by chance, I saw the call_user_func_array() function in PHP again in the official documentation of CodeIgniter. I also encountered it in the code of the discuz forum last year. I checked this function online today. Usage, let's share with you the usage of the call_user_func_array and call_user_func functions, and also provide usage instructions for the func_get_args() function and func_num_args() function.
The call_user_func function is used when a function needs to be called dynamically. This function has two uses, which are explained below:
(1) Call the lonely function:
<?php function funa($b,$c){ echo $b; echo $c; } call_user_func('funa',"111","222"); call_user_func('funa',"333","444"); //结果输出:111 222 333 444 //大家有没有发现,这个用法有点像javascript中的call方法 ?>
(2) Call the function inside the class:
<?php class a{ function b(){ $args=func_get_args(); $num=func_num_args(); print_r($args); echo $num; } } call_user_func(array("a","b"),"111","222"); ?>
For the above example, the output is as follows:
Array
(
[0] => 111
[1] => 222
)
2
Tip: The func_get_args() function gets the parameters passed into the function and returns an array. The func_num_args() function gets the number of parameters passed into the function.
Let’s take a look at call_user_func_array. This function is also used when a function needs to be called dynamically. Its usage is similar to the call_user_func function, except that the parameter is passed in an array. The example is as follows:
<?php function a($b,$c){ echo $b;echo $c; } call_user_func_array('a',array("111","222")); //结果输出:111 222 ?>
The call_user_func_array function can also call methods inside the class, such as:
<?php Class ClassA{ function bc($b,$c){ $bc=$b + $c;echo $bc; } } call_user_func_array(array('ClassA','bc'),array("111","222")); //结果输出:333 ?>
Let’s look at another example of dynamically calling a function:
09e92399e9b894de3f423252b8b31264
Readers can run the above examples themselves and the impression will be even more profound.