call_user_func_array

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

call_user_func_array调用回调函数,并把一个数组参数作为回调函数的参数

说明

call_user_func_array(callable $callback, array $param_arr): mixed

把第一个参数作为回调函数(callback)调用,把参数数组作(param_arr)为回调函数的的参数传入。

参数

callback

被调用的回调函数。

param_arr

要被传入回调函数的数组,这个数组得是索引数组。

返回值

返回回调函数的结果。如果出错的话就返回false

更新日志

版本 说明
5.3.0 对面向对象里面的关键字的解析有所增强。在此之前,使用两个冒号来连接一个类和里面的一个方法,把它作为参数来作为回调函数的话,将会发出一个E_STRICT的警告,因为这个传入的参数被视为静态方法。

范例

示例 #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(24))); /* 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

注释

注意:

PHP 5.4之前,如果param_arr里面的参数是引用传值,那么不管原函数默认的各个参数是不是引用传值,都会以引用方式传入到回调函数。虽然以引用传值这种方式来传递参数给回调函数,不会发出不支持的警告,但是不管怎么说,这样做还是不被支持的。并且在PHP 5.4里面被去掉了。而且,这也不适用于内部函数,for which the function signature is honored。如果回调函数默认设置需要接受的参数是引用传递的时候,按值传递,结果将会输出一个警告。call_user_func() 将会返回 false(there is, however, an exception for passed values with reference count = 1, such as in literals, as these can be turned into references without ill effects — but also without writes to that value having any effect —; do not rely in this behavior, though, as the reference count is an implementation detail and the soundness of this behavior is questionable)。

注意:

在函数中注册有多个回调内容时(如使用 call_user_func()call_user_func_array()),如在前一个回调中有未捕获的异常,其后的将不再被调用。

参见

7i24.Com