如何在PHP中实现回调?
毕业设计
1
回调是如何用 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
支持以上所有。 -
回调的实现是这样完成的
// This function uses a callback function. function doIt($callback) { $data = "this is my data"; $callback($data); } // This is a sample callback function for doIt(). function myCallback($data) { print 'Data is: ' . $data . " "; } // Call doIt() and pass our sample callback function's name. doIt('myCallback');
显示:数据是:这是我的数据
发表回复