Home >Backend Development >PHP Tutorial >How Can I Use Callbacks Effectively in PHP?

How Can I Use Callbacks Effectively in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 20:34:30218browse

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:

<code class="php">if (is_callable($cb2)) {
    $returnValue = call_user_func($cb2, $arg1, $arg2);
}</code>

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. ['VendorPackageFoo', '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.

The above is the detailed content of How Can I Use Callbacks Effectively in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn