PHP functions call_user_func and call_user_func_array
- 2021-01-18 06:22:04
- OfStack
The call_user_func function is used when a function needs to be called dynamically. This function can be used in two ways:
The first is to call a lonely function:
<?php
function funa($b,$c)
{
echo $b;
echo $c;
}
call_user_func('funa', "111","222");
call_user_func('funa', "333","444");
// According to 111 222 333 444
// Do you notice that it's a little bit like javascript In the call Method, hey hey
?>
The second way is to call a function inside a 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");
?>
The func_get_args() function gets the number of arguments passed to the function and returns an array. The func_num_args() function gets the number of arguments passed to the function.
Now let's look at the call_user_func_array function
This function is also used when you need to call a function dynamically. It is used much like the call_user_func function, except that the arguments are passed in arrays.
<?php
function a($b, $c)
{
echo $b;
echo $c;
}
call_user_func_array('a', array("111", "222"));
// According to 111 222
?>
The call_user_func_array function can also call methods within a class
<?php
Class ClassA
{
function bc($b, $c) {
$bc = $b + $c;
echo $bc;
}
}
call_user_func_array(array( ' ClassA','bc'), array( " 111 " , " 222 " ));
// According to 333
?>
Here's another example of a dynamic function call:
<?php
function otest1 ($a)
{
echo( '1 A parameter ' );
}
function otest2 ( $a, $b)
{
echo( '2 A parameter ' );
}
function otest3 ( $a ,$b,$c)
{
echo( '3 A! ' );
}
function otest (){
$args = func_get_args();
$num = func_num_args();
call_user_func_array( 'otest'.$num, $args );
}
otest("11");
otest("11","22");
otest("11","22","33");
?>