Tag Archives: PHP callbacks

PHP Callbacks

A callback is a function that is passed to another segment of code, service or process in order for that segment of code, service or process to call the function at some later point in time when a certain condition has been met. A typical use for a callback is handling information that is requested from a web service like the Google Custom Search API.

A callback function is passed by its name as a string using the call_user_func() helper function. Object methods and static class methods can also be called back using call_user_func().

I will go ahead and give some examples of each of these three ways to call a callback by creating a simple function and a class that has both a static method and a normal method (that must be called by an instantiated object).

Callbacks1
Callbacks1
Callbacks1

These first three examples were to demonstrate the three main ways that call_user_func() can be used to pass callbacks. I will continue on with another example to demonstrate a more practical use for callbacks, using them to process data from the Google API.

Callbacks1
Callbacks1

You can imagine all the other practical uses for callbacks from writing a payment confirmation to your database after a customer makes a successful purchase from your web site’s payment gateway, or writing search results to your database as is implied in the example above.