回调如何用PHP编写?
该手册可互换地使用术语“回调”和“可调用”,但是,“回调”传统上是指充当函数指针的字符串或数组值,引用函数或类方法以供将来调用。自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
支持以上所有内容。
参见:http : //php.net/manual/en/language.types.callable.php
注释/注意事项:
['Vendor\Package\Foo', 'method']
call_user_func
不支持通过引用传递非对象,所以您可以使用call_user_func_array
,或者在以后的PHP版本,保存回调到var和使用直接的语法:$cb()
;__invoke()
方法(包括匿名函数)的对象属于“可调用”类别,并且可以按相同方式使用,但是我个人不将其与传统“回调”术语相关联。create_function()
创建全局函数并返回其名称。它是包装器,eval()
应改用匿名函数。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句