php call_user_func(),call_user_func_array()使用和区别

call_user_func(),call_user_func_array() 是用来调用回调函数


一般使用如下:
//调用的是静态方法
<?php
namespace Foobar;
class Foo {
    static public function test($param) {
        print "Hello world! \$param \n";
    }
}


$param = 'param'
call_user_func(__NAMESPACE__ .'\Foo::test',$param);
call_user_func(array(__NAMESPACE__ .'\Foo', 'test'), $param);
call_user_func([Foo::class, 'test'], $param);
?>

//调用非静态方法,通常要实例化
<?php
namespace Foobar;
class Foo {
    public function test($param) {
        print "Hello world! \$param \n";
    }
}

$foo = new Foo();
$param = 'param'
call_user_func(array($foo, 'test'), $param);
//如果需要传递多个参数 :call_user_func(array($foo, 'test'), $param, $param1, $param2);
?>
call_user_func(),call_user_func_array() 主要区别,参数格式。
//call_user_func(array($foo, 'test'), [$param, $param1, $param2])这种格式会把后面数组作为一个参数传递过去
//call_user_func_array(array($foo, 'test'), [$param, $param1, $param2]) 这种格式会作为三个参数传递给回调函数,如果存在key ,忽略。


tips:一般来说

# Benchmark (2 million iterations)

# Operation                    Seconds
# Literal function          1.218
# Variable function         1.305
# call_user_func()          2.734
# call_user_func_array()    3.386
可以看到,变量函数和普通函数调用(literal function)速度差别不大,和call_user_func相差有一倍以上,而call_user_func_array则要更慢。所以你给的代码才会尽量避免使用call_user_func_array而更倾向于使用变量函数。因为只有很少的函数会有5个以上的参数,所以上面代码里才把1到5个函数的调用用变量函数来写,而只留下小部分的函数用call_user_func_array调用,从而最大的加快程序执行速度。

其实,这些函数的效率差异不会有想象的那么大,上面的benchmark是迭代200万次的结果,如果你的程序只会调用'call_user_func_array'几千次或以下,这些差异将会非常小(大概是0.002秒左右),没必要在这些地方做优化。

参考: https://segmentfault.com/q/1010000005268876

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值