Quick Guide To PHP Callback Function
The goal of this article is to learn PHP callback functions, as well as how to create and use them. Furthermore, we will cover some further advanced topics, such as the use of anonymous functions and closures.
As a PHP developer, it is important to understand callback functions, since they allow you to create applications that are more dynamic and flexible.
An argument of PHP callback function is passed to another function as an argument, and that function is then responsible for executing the callback function.
There are a variety of purposes for which PHP callback functions can be used, such as handling events, filtering data, and mapping data.
No matter if you are a new PHP developer or have been working with PHP for a long time, this article will help you better understand how to make your PHP code more powerful and flexible by using PHP callback functions.
PHP Callback Functions
The term callback function (or more commonly “callback“) refers to a function that is passed as an argument to another function in order to perform an action.
You can use any existing function as a callback. A callback function can be created by passing a string containing the name of the callback function as the argument to the next function that is being called.
In the following example, for each string in an array, you can pass a callback function to PHP’s array_map() function for it to calculate its length:
User Defined Callback Functions
A callback function can also be passed as an argument to any user-defined function or method.
If you want to call a callback function within a user-defined function or method, you will need to have parentheses around the variable and pass its arguments as you would normally do with a function.
Callbacks can be sent from user-defined functions in the following manner:
In above example, printFunction() is a higher-order function that accepts two arguments: a string and a callback function name ($format).
The printFunction() function takes the $string argument and calls the callback function passed as $format with $string as an argument. The result of the callback function is then printed to the screen using echo.
In the given code, two callback functions are defined:
firstname() and lastname().
These functions simply return the string that is passed as an argument.
The printFunction() function is then called twice with different strings and callback functions.
- The first call passes the string Mark and the callback function firstname() as arguments.
- The second call passes the string Zuckerberg and the callback function lastname() as arguments.
When the code is executed, the output will be:
This is because the printFunction() function calls the respective callback function (firstname() or lastname()) with the given string argument, and then prints the result to the screen.