0
0
PhpConceptBeginner · 3 min read

What is Callback Function in PHP: Simple Explanation and Example

A callback function in PHP is a function passed as an argument to another function, which is then called inside that function. It allows you to customize behavior by letting one function call another function dynamically.
⚙️

How It Works

Think of a callback function like giving someone a phone number to call when they finish a task. In PHP, you pass a function's name or an anonymous function as an argument to another function. The receiving function can then "call back" this function at the right moment.

This lets you write flexible code where one function controls the flow but lets another function decide what to do at a certain point. It’s like telling a friend, "When you finish cleaning, call me," so you can react to their action.

💻

Example

This example shows a function that takes a callback and calls it with a message.

php
<?php
function greet($name, $callback) {
    echo "Hello, $name! ";
    $callback();
}

$callbackFunction = function() {
    echo "Welcome to PHP callbacks.";
};

greet('Alice', $callbackFunction);
?>
Output
Hello, Alice! Welcome to PHP callbacks.
🎯

When to Use

Use callback functions when you want to make your code more flexible and reusable. They are common in sorting, filtering, or event handling where you want to specify what happens at certain points without changing the main function.

For example, PHP’s usort() function uses a callback to decide how to compare items. Callbacks are also useful in asynchronous programming or when you want to customize behavior in libraries or frameworks.

Key Points

  • A callback is a function passed as an argument to another function.
  • It allows dynamic execution of code inside the receiving function.
  • Callbacks increase flexibility and reusability of code.
  • They are widely used in sorting, filtering, and event-driven programming.

Key Takeaways

A callback function is passed to another function to be called later.
Callbacks let you customize behavior without changing the main function.
They are useful in sorting, filtering, and event handling.
PHP supports callbacks as named functions or anonymous functions.
Using callbacks makes your code more flexible and reusable.