call_user_func基本用法
mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )
第一个参数 callback 是被调用的回调函数(一般为闭包函数),其余参数是回调函数的参数。
参数:
callback:将被调用的回调函数。parameter:将要传入callback回调函数的参数。
<?php
function increment(&$var)
{
$var++;
}
$a = 0;
call_user_func('increment', $a);
echo $a."\n";
call_user_func_array('increment', array(&$a));
echo $a."\n";
以上例程会输出:
0
1
call_user_func() 在命名空间中的使用
<?php
namespace Foobar;
class Foo {
static public function test() {
print "Hello world!\n";
}
}
call_user_func(__NAMESPACE__ .'\Foo::test');
call_user_func(array(__NAMESPACE__ .'\Foo', 'test'));
?>
__NAMESPACE__为魔术常量,其值为包含当前命名空间名称的字符串
以上例程会输出:
Hello world!
Hello world!
call_user_func()调用类里面的方法使用
<?php
class myclass {
static function say_hello()
{
echo "Hello!\n";
}
}
$classname = "myclass";
call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello');
$myobject = new myclass();
call_user_func(array($myobject, 'say_hello'));
?>
既可以用未实例化的类去调用,也可以用实例化的类去调用。
以上例程会输出:
Hello!
Hello!
Hello!
call_user_func()闭包函数使用
<?php
class myclass {
static function say_hello()
{
echo "Hello!\n";
}
}
function test(Closure $closure)
{
$className = "myclass";
call_user_func($closure, $className, array($className,'say_hello'));
}
test(function($argc,$argv){
$argv();
echo $argc;
});
?>
以上例程会输出:
Hello!
myclass

被折叠的 条评论
为什么被折叠?



