call_user_func_array — 调用回调函数,并把一个数组参数作为回调函数的参数
范例
1.call_user_func_array()例子
<?php
function foobar($arg, $arg2) {
echo __FUNCTION__, " got $arg and $arg2\n";
}
class foo {
function bar($arg, $arg2) {
echo __METHOD__, " got $arg and $arg2\n";
}
}
// Call the foobar() function with 2 arguments
call_user_func_array("foobar", array("one", "two"));
// Call the $foo->bar() method with 2 arguments
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));
?>
以上例程的输出类似于:
foobar got one and two foo::bar got three and four
2 call_user_func_array()使用命名空间的情况
<?php
namespace Foobar;
class Foo {
static public function test($name) {
print "Hello {$name}!\n";
}
}
// As of PHP 5.3.0
call_user_func_array(__NAMESPACE__ .'\Foo::test', array('Hannes'));
// As of PHP 5.3.0
call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Philip'));
?>
以上例程的输出类似于:
Hello Hannes! Hello Philip!
3 把完整的函数作为回调传入call_user_func_array()
<?php
$func = function($arg1, $arg2) {
return $arg1 * $arg2;
};
var_dump(call_user_func_array($func, array(2, 4))); /* As of PHP 5.3.0 */
?>
以上例程会输出:
int(8)
4 传引用
<?php
function mega(&$a){
$a = 55;
echo "function mega \$a=$a\n";
}
$bar = 77;
call_user_func_array('mega',array(&$bar));
echo "global \$bar=$bar\n";
?>
以上例程会输出:
function mega $a=55 global $bar=55