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

<?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

转载于:https://my.oschina.net/banbo/blog/464264

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值