回调是如何用 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
请参阅: http: //php.net/manual/en/language.types.callable.php
注释/注意事项:
['Vendor\Package\Foo', 'method']
__invoke()
create_function()
eval()