如何在PHP中实现回调? [英] How do I implement a callback in PHP?
问题描述
如何用PHP编写回调?
How are callbacks written in PHP?
推荐答案
该手册可互换地使用术语回调"和可调用",但是,回调"传统上是指类似于函数指针,引用函数或类方法以供将来调用.自PHP 4以来,这已允许使用函数式编程的某些元素.其风味是:
The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a function pointer, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are:
$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');
这是通常使用可调用值的安全方法:
This is a safe way to use callable values in general:
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
支持上述所有条件.
Modern PHP versions allow the first three formats above to be invoked directly as $cb()
. call_user_func
and call_user_func_array
support all the above.
请参阅: 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()
的包装,应改用匿名函数.
- If the function/class is namespaced, the string must contain the fully-qualified name. E.g.
['Vendor\Package\Foo', 'method']
call_user_func
does not support passing non-objects by reference, so you can either usecall_user_func_array
or, in later PHP versions, save the callback to a var and use the direct syntax:$cb()
;- Objects with an
__invoke()
method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don't associate these with the legacy "callback" term. - The legacy
create_function()
creates a global function and returns its name. It's a wrapper foreval()
and anonymous functions should be used instead.
这篇关于如何在PHP中实现回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!