PHP的可调用类型(callable)总结
// 1 普通函数
call_user_func('my_function');
// 2类的静态方法
call_user_func(['MyClass', 'myCallbackMethod']);
// 3对象方法
call_user_func([new MyClass(), 'myCallbackMethod']);
//4类的静态方法(2)
call_user_func('MyClass::myCallbackMethod');
//5匿名函数
call_user_func(function(){echo '匿名函数';});
//6箭头函数
call_user_func(fn() =>print('箭头函数'));
//7相对关系
call_user_func(array('B', 'parent::who'));
// 8: Objects implementing __invoke can be used as callables
class C {
public function __invoke($name) {
echo 'Hello ', $name, "\n";
}
}$c = new C();
call_user_func($c, 'PHP!');
?>
其它用法:
call_user_func(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // As of PHP 5.3.0
class myclass {
static function say_hello()
{
echo "Hello!\n";
}
}
$classname = "myclass";
call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3
$myobject = new myclass();
call_user_func(array($myobject, 'say_hello'));
评论 (0)