call_user_func()的用法

call_user_func — 把第一个参数作为回调函数调用

说明
mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )
第一个参数 callback 是被调用的回调函数,其余参数是回调函数的参数。

参数
callback
将被调用的回调函数(callable)。

parameter
0个或以上的参数,被传入回调函数,可以是数组。

例1:函数

function test($var) 
{
    return $var;
}

echo call_user_func('test', 'hello word');
//输出 hello word

例2: 类/方法

class myclass {
    static function say_hello($var)
    {
        echo $var;
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'),'hello word'); // 输出 hello word
call_user_func($classname .'::say_hello','hello word'); // 输出 hello word
$myobject = new myclass();  
call_user_func(array($myobject, 'say_hello'),'hello word') // 输出 hello word

例3:匿名函数

call_user_func(function($arg) { 
    echo $arg;
}, 'test');
//输出test

猜你喜欢

转载自www.cnblogs.com/yangye88/p/9056343.html