"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Use Callbacks Effectively in PHP?

How Can I Use Callbacks Effectively in PHP?

Published on 2024-11-09
Browse:428

How Can I Use Callbacks Effectively in PHP?

Implementing Callbacks in PHP

The term "callback" in PHP encompasses both strings and arrays that operate as function pointers. In PHP 4, the following syntax emerged:

  • $cb1 = 'someGlobalFunction';
  • $cb2 = ['ClassName', 'someStaticMethod'];
  • $cb3 = [$object, 'somePublicMethod'];

Although PHP 5.2.3 introduced callable syntax, strings containing such syntax cannot be directly invoked. Legacy syntax for PHP 4 includes:

  • $cb3 = array(&$object, 'somePublicMethod');

The following code snippet demonstrates safe usage of callable values:

if (is_callable($cb2)) {
    $returnValue = call_user_func($cb2, $arg1, $arg2);
}

Modern PHP versions support invoking the first three formats above directly as $cb(). Additionally, call_user_func and call_user_func_array support all the presented formats.

Notes and Caveats:

  • Namespaced functions/classes require fully-qualified names, e.g. ['Vendor\Package\Foo', 'method'].
  • call_user_func does not support passing non-objects by reference. Use call_user_func_array or $cb(); in later PHP versions.
  • Objects with an __invoke() method (including anonymous functions) can be used as callbacks, but are not typically associated with the traditional "callback" term.
  • Legacy create_function() creates a global function and returns its name. Use anonymous functions instead.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3