如何在PHP中实现回调?
2022-08-30 06:27:52
回调是如何用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
不支持通过引用传递非对象,因此您可以使用或在以后的 PHP 版本中将回调保存到 var 并使用直接语法:call_user_func_array
$cb()
;__invoke()方法的对象
(包括匿名函数)属于“可调用”类别,可以以相同的方式使用,但我个人并不将它们与传统的“回调”术语相关联。create_function()
eval()
在 PHP 5.3 中,您现在可以执行以下操作:
function doIt($callback) { $callback(); }
doIt(function() {
// this will be done
});
最后是一个很好的方法。PHP的一个很好的补充,因为回调很棒。