PHP Callbacks and Callback Functions

php-callbacksI only encountered callbacks recently, and spent many hours surfing the web for a nice simple explanation.

Eventually I think I made sense of it and so here is my attempt to explain what they are and how they work.



What is a Callback?

A Callback (or callback function) is a function that is called when another function has finished.

So imagine 2 functions f1 and f2.

If f1 is our callback then function f2 executes and does what it has to do, then before it finished is calls function f1.

My understanding of the terminology is:

  • f1 is our callback function
  • f2 is a function that accepts a callback function name as a parameter

Implementing Callbacks

It’s relatively easy to implement this type of functionality.

We could write the code like this:Callback-functions-overview-diagram1

 

Although the above shows the basic outline, the implementation is more like this:

Callback-functions-overview-diagram2

Notice that The callback function name is passed ( as a string), as an argument to function f2() along with any other arguments.

The function (f1) is called using the code $callback();

In PHP it is possible to use a variable for a function name:

So

$fname=”f1″;

$fname();

is valid and equivalent to:

f1();

See variable functions php manual for more details.

Here is an example implementation:

php-callback-implemtation-example

Note: in the example above I have omitted error checking. Usually you would check that the function name represents a function before you try to call it. Like this:

if(is_callable($callback)) {
return $callback($otherarguments);

}

WordPress Example

Hooks and filters use callbacks. Here is the add_action function showing what parameters it expects. The second parameter is a function (a callback).

add_action_callbackIf you look at the WordPress Code associated with many WordPress functions that accept a callback function name then they often pass the callback function name on to another function.

Below is the syntax for the register_setting function and the actual code. You can see that the callback function name is then used by the add filter function.

register_setting_function_usage

Summary

PHP allows you to pass a function name as a parameter or argument to a function. A callback is a function that is called by another function, and is passed to that function using the function name.

Resources:

Related tutorials

Did this Tutorial Help? Please Rate
[Total: 2 Average: 5]