Callback functions

A callback function is simply a function that you do not call yourself. Instead, you hand it over to another function, and that other function decides when and how to execute it.

In PHP, functions are “first-class citizens”, which means they can be treated like values. You can store a function name in a variable, pass it as an argument, and call it dynamically later.

A callback can be:

  • a named function, passed as a string containing its name
  • an anonymous function, defined inline and passed directly

When you pass a named function as a callback, you do not include parentheses. You are not calling it yet. You are just giving PHP a reference to that function. The function that receives the callback will be responsible for calling it.

Anonymous functions are useful when the logic is short and only needed once. Instead of defining a function elsewhere, you define it inline at the moment you pass it as a callback.

Some built-in PHP functions are designed to work with callbacks. A common example is array_map(), which applies a callback to each element of an array and returns a new array with the results.

Callbacks are not limited to built-in functions. User-defined functions can also accept callbacks as arguments. Inside such functions, the callback is executed by treating the variable as a function and adding parentheses, passing arguments just like a normal function call.

This pattern allows behavior to be customized from the outside. Instead of hardcoding logic inside a function, you pass the logic in as a callback, making the function more flexible and reusable.