您的位置:首页 > 其它

使用 call_user_func_array() 来回调执行函数和直接调用函数的区别是什么?

2015-06-08 17:48 573 查看
<?php
header("Content-type:text/html;charset=utf-8");

function test($name, $age) {
echo $name . ' == ' . $age . '<br />';
}

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() 函数最有优势的地方!)

<?php
header("Content-type:text/html;charset=utf-8");

function playVideo($type, $src)
{
echo "{$type} : I will watch {$src}<br />";
}

function playAudio($type, $src, $artist)
{
echo "{$type} : I will listen to {$artist}'s {$src}<br />";
}

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() 函数可能稍微简洁些吧:

<?php
header("Content-type:text/html;charset=utf-8");

class Test {
public function a() {
$args = func_get_args($name, $age);
echo "{$name}今年{$age}岁了! <br />";
}
}

// 很简洁
call_user_func_array(array(new Test(),'a'), array('小花', 18));

// 直接调用稍微麻烦些
$test = new Test();
$test->a('小花', 18); // php 不支持 new class()->method() 语法

在类方法参数个数不确定时,还是得使用 call_user_func_array() !

参考:http://segmentfault.com/q/1010000000469520
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: