![]() |
VOOZH | about |
In PHP, the callback functions are related to the dynamic behavior and flexibility in code execution. They are used to pass custom logic or functions as arguments to other functions, letting developers change how a function behaves without changing its main structure. This makes the code more reusable, modular, and adaptable to different situations.
In this article, we will discuss PHP callback functions, their types, and how they are used.
A callback function is simply a function that you can pass as an argument to another function and invoke at a later time. In PHP, callbacks are most commonly used when you need to allow dynamic behavior for functions, allowing users or other functions to determine what specific code should run.
A callback function can be:
Now, let us understand with the help of the example:
Hello, GFG!
In this example:
Below are the following types of Callback functions in PHP.
In the simplest form, you can pass the name of a function as a string to another function, and that function will be called when the callback is invoked.
1 4 9 16 25
In this example:
In object-oriented PHP, you can pass the method of an object as a callback by using an array format. This allows you to dynamically choose which method to call.
Hello, GFG!
In this example:
An anonymous function can be used as a callback in situations where you need to define a function on the fly, without declaring it beforehand.
Hello, GFG!
In this example:
PHP provides some built-in functions to work with callbacks more effectively. Here are a few:
This function allows you to call a callback function passed as a string or an array.
Hello, GFG!
In this example, call_user_func() is used to invoke the function sayHello() with the parameter 'GFG. '
This function is similar to call_user_func(), but it allows you to pass multiple arguments as an array.
30
In this example, call_user_func_array() is used to pass the arguments [10, 20] to the function sum(), which will return 30.
array_map() is a built-in PHP function that applies a callback to each element of an array.
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
In this example, array_map() applies the anonymous function to each element of the array $numbers, doubling each number.