回调如何用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支持以上所有内容。
$cb()
call_user_func
call_user_func_array
注释/注意事项:
['Vendor\Package\Foo', 'method']
__invoke()
create_function()
eval()