php call_user_func_array

call_user_func_array
(PHP 4 >= 4.0.4, PHP 5, PHP 7)
call_user_func_array — 调用回调函数,并把一个数组参数作为回调函数的参数
说明
mixed call_user_func_array ( callable $callback , array $param_arr )
把第一个参数作为回调函数(callback)调用,把参数数组作(param_arr)为回调函数的的参数传入。
参数
 
callback
被调用的回调函数。
param_arr
要被传入回调函数的数组,这个数组得是索引数组。
 
返回值
返回回调函数的结果。如果出错的话就返回FALSE
更新日志
版本
说明
5.3.0
对面向对象里面的关键字的解析有所增强。在此之前,使用两个冒号来连接一个类和里面的一个方法,把它作为参数来作为回调函数的话,将会发出一个E_STRICT的警告,因为这个传入的参数被视为静态方法。
 
范例
 
Example #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
Example #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!
Example #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)
Example #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
 
注释
Note:
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)。 
 

猜你喜欢

转载自www.cnblogs.com/hnhycnlc888/p/9887691.html