该手册可互换地使用术语“回调”和“可调用”,但是,“回调”传统上是指充当函数指针的字符串或数组值,并引用函数或类方法以供将来调用。自PHP
4以来,已经允许使用函数式编程的某些元素。
$cb1 = 'someGlobalFunction';$cb2 = ['ClassName', 'someStaticMethod'];$cb3 = [$object, 'somePublicMethod'];// this syntax is callable since PHP 5.2.3 but a string containing it// cannot be called directly$cb2 = 'ClassName::someStaticMethod';$cb2(); // fatal error// legacy syntax for PHP 4$cb3 = array(&$object, 'somePublicMethod');
通常,这是使用可调用值的安全方法:
if (is_callable($cb2)) { // Autoloading will be invoked to load the class "ClassName" if it's not // yet defined, and PHP will check that the class has a method // "someStaticMethod". Note that is_callable() will NOT verify that the // method can safely be executed in static context. $returnValue = call_user_func($cb2, $arg1, $arg2);}现代PHP版本允许上面的前三种格式直接作为调用
$cb()。
call_user_func并
call_user_func_array支持以上所有内容。
注释/注意事项:
- 如果函数/类已命名空间,则字符串必须包含标准名称。例如
['VendorPackageFoo', 'method']
call_user_func
不支持通过引用传递非对象,所以您可以使用call_user_func_array
,或者在以后的PHP版本,保存回调到var和使用直接的语法:$cb()
;- 具有
__invoke()
方法的对象(包括匿名函数)属于“可调用”类别,并且可以按相同方式使用,但是我个人不将其与传统“回调”术语相关联。 - 旧版
create_function()
创建全局函数并返回其名称。它是包装器,eval()
应改用匿名函数。



