mixed call_user_func ( callable $callback
[, mixed $parameter
[, mixed $...
]]
)
Calls the callback given by the first parameter and passes the remaining parameters as arguments.
调用由第一参数给出的回调函数,并将其余的参数作为回调函数的参数。
mixed call_user_func_array ( callable $callback
, array $param_arr
)
Calls
the callback given by the first parameter with the parameters in param_arr.
调用由第一参数给出的回调函数,并将数组param_arr的参数作为回调函数的参数。
Returns
the return value of the callback, or FALSE on error.
返回回调函数的返回值,出错时返回FALSE。
由上面手册给的说明来看,call_user_func 和 call_user_func_array 函数功能基本差不多。
1. 需要注意的一点事,call_user_func()的回调函数参数不能通过引用传递,而 call_user_func_array ()是可以的。比如下面这个例子:
2.
在函数中注册有多个回调内容时(如使用 call_user_func() 与 call_user_func_array()),如在前一个回调中有未捕获的异常,其后的将不再被调用。
<?php error_reporting(E_ALL); function increment(&$var) { $var++; } $a = 0; call_user_func(‘increment‘, $a); echo $a."\n"; call_user_func_array(‘increment‘, array(&$a)); // You can use this instead before PHP 5.3 echo $a."\n"; ?>上面的程序会输出:
0
1
下面我们通过例子来了解下call_user_func和call_user_func_array 具体怎么用
<?php function barber($type) //参数可以有多个 { echo "You wanted a $type haircut, no problem\n"; } call_user_func(‘barber‘, "mushroom"); call_user_func(‘barber‘, "shave"); ?>上面程序输出:
You wanted a mushroom haircut, no problem You wanted a shave haircut, no problem
<?php function barber($type,$type2) //参数可以有多个 { echo "You wanted a $type haircut, no problem $type2 \n"; } call_user_func_array(‘barber‘, array("mushroom","!")); call_user_func_array(‘barber‘, array("shave","!")); ?>
上面程序输出:
You wanted a mushroom haircut, no problem ! You wanted a shave haircut, no problem !
<?php class myclass { function say_hello($name) { echo "Hello $name"; } } $classname = "myclass"; //调用类内部的函数需要使用数组方式 array(类名,方法名) call_user_func(array($classname, ‘say_hello‘), ‘World!‘); call_user_func_array(array($classname, ‘say_hello‘), array("PHP!")); //print Hello World! //print Hello PHP! ?>
<?php namespace Foobar; class Foo { static public function test() { print "Hello world!\n"; } } call_user_func(__NAMESPACE__ .‘\Foo::test‘); // As of PHP 5.3.0 call_user_func(array(__NAMESPACE__ .‘\Foo‘, ‘test‘)); // As of PHP 5.3.0 //print Hello world! //print Hello world! ?>
<?php call_user_func(function($arg) { print "[$arg]\n"; }, ‘test‘); /* As of PHP 5.3.0 */ //print [test] ?>
<?php function Benchmark() { foreach(func_get_args() as $function) { $st = microtime(true); call_user_func($function); $et = microtime(true); echo sprintf("Time: %f", $et - $st) . ‘<br />‘; } } Benchmark(function() { for ( $i = 0; $i <= 10000; $i++ ) { } }, function() { $i = 0; while ( $i <= 10000 ) { $i++; } }); ?> //print Time: 0.001652 //print Time: 0.001458
http://www.php.net/manual/zh/function.call-user-func.php
http://www.php.net/manual/zh/function.call-user-func-array.php
call_user_func和call_user_func_array的用法详解,布布扣,bubuko.com
call_user_func和call_user_func_array的用法详解
原文:http://blog.csdn.net/risingsun001/article/details/21696585