header("Content-type:text/html;charset=utf-8");
function test($name, $age) {
echo $name . ' == ' . $age . '
';
}
test('小花', 18); // 直接调用
call_user_func_array('test', array('小花', 18)); // 使用 call_user_func_array
对比了半天觉得根本没必要用 call_user_func_array() 函数,直接调用反而更方便!
但是如果场景是这样的:
1、你要调用的函数名是未知的(PHP 支持变量调用函数和类,如 <?php $a = 'test'; $a(); ?>,所以这个不算 call_user_func_array() 函数的优势)
2、要调用函数的参数类型及个数也是未知的(这个才是使用 call_user_func_array() 函数最有优势的地方!)
header("Content-type:text/html;charset=utf-8");
function playVideo($type, $src)
{
echo "{$type} : I will watch {$src}
";
}
function playAudio($type, $src, $artist)
{
echo "{$type} : I will listen to {$artist}'s {$src}
";
}
function play()
{
$args = func_get_args();
call_user_func_array('play'.$args[0], $args);
// PHP 支持变量调用函数和类
// $func_name = 'play'.$args[0];
// $func_name($args[0], $args[1]); // 参数个数不确定,playVideo 需要 2 个参数,playAudio 需要 3 个参数,而 call_user_func_array 直接传递参数数组就完全不用考虑这个问题了
// call_user_func('play'.$args[0], $args[0], $args[1]); // 和上面参数个数的缺点一样,所以最好使用 call_user_func_array 函数
}
play('Video','功夫.rmvb');
play('Audio','简单爱.mp3', 'Jay');
还有个场景,在调用对象的方法时使用call_user_func_array() 函数可能稍微简洁些吧:
header("Content-type:text/html;charset=utf-8");
class Test {
public function a() {
$args = func_get_args($name, $age);
echo "{$name}今年{$age}岁了!
";
}
}
// 很简洁
call_user_func_array(array(new Test(),'a'), array('小花', 18));
// 直接调用稍微麻烦些
$test = new Test();
$test->a('小花', 18); // php 不支持 new class()->method() 语法
在类方法参数个数不确定时,还是得使用 call_user_func_array() !