php - 如何在 PHP 中实现回调?

标签 php

如何用 PHP 编写回调函数?

最佳答案

本手册交替使用术语“回调”和“可调用”,然而,“回调”传统上指的是一个字符串或数组值,其行为类似于 function pointer ,引用函数或类方法以供将来调用。自 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_funccall_user_func_array 支持以上所有。

见:http://php.net/manual/en/language.types.callable.php

注意事项/注意事项:

  1. 如果函数/类是命名空间的,则字符串必须包含完全限定的名称。例如。 ['Vendor\Package\Foo', 'method']
  2. call_user_func 不支持通过引用传递非对象,因此您可以使用 call_user_func_array 或者在以后的 PHP 版本中,将回调保存到 var 并使用直接语法:$cb();
  3. 带有 __invoke() 的对象方法(包括匿名函数)属于“可调用”类别,并且可以以相同的方式使用,但我个人不会将这些与旧的“回调”术语联系起来。
  4. 旧版 create_function() 创建一个全局函数并返回其名称。它是 eval() 的包装器,应该使用匿名函数。

关于php - 如何在 PHP 中实现回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48947/

相关文章:

php - 如果将所需值插入数据库,则永久禁用提交按钮 - php

php - 我该如何优化这个 MySQL 查询?

php - Laravel将可变成功消息从存储库传递回 Controller

c# - Curl - 获取包含图像和 css 的页面

php - 将业务逻辑与 PHP Doctrine 2 分开

php - MYSQL : Getting error in TRIGGER

PHP:未定义索引 - 但我定义了它们? :S

php - 将 URL 转换为屏幕截图(脚本)

php - 使用不同类型的用户在mySQL上创建角色

php - 如何将MySQL表中的图像以表格式显示到PHP页面?