call_user_func_array()

动态调用具有参数的用户函数或者类方法

首字母:C

函数call_user_func_array()用于动态调用具有参数的用户函数或者类方法。

用法: call_user_func_array ( callable $callback , array $param_arr ) : mixed

参数:

  1. $callback:要调用的函数或方法,可以是以字符串形式表示的函数名、类名和方法名的数组,或者是匿名函数。
  2. $param_arr:包含参数的数组。

返回值: 返回调用函数或方法的返回值。

示例:

  1. 使用全局函数:
function sum($a, $b) {
 return $a + $b;
}
$args = [2, 3];
$result = call_user_func_array('sum', $args);
echo $result; // 输出: 5
  1. 使用类方法:
class Math {
 public function add($a, $b) {
 return $a + $b;
 }
}
$math = new Math();
$args = [2, 3];
$result = call_user_func_array([$math, 'add'], $args);
echo $result; // 输出: 5
  1. 使用匿名函数:
$callback = function($a, $b) {
 return $a + $b;
}
$args = [2, 3];
$result = call_user_func_array($callback, $args);
echo $result; // 输出: 5

在上述示例中,通过call_user_func_array()函数动态调用了sum()函数、Math类的add()方法以及匿名函数,传递参数给这些函数,并获取返回值。

同首字母函数