Home Posts How to use callback function in PHP?

How to use callback function in PHP?

feature image
Last updated on Aug 18, 2025

A callback function in PHP is a function that is passed as an argument to another function, allowing the receiving function to execute (call) the passed function at a later time or under specific conditions. This provides dynamic behavior and flexibility, making code more reusable and modular.

# How Callback Functions Work in PHP

  • Named Function Callback: You can pass the name of a function as a string to another function, which then calls it.

function greet($name) {
    return "Hello, " . $name . "!";
}
function processUser($callback) {
    $name = "User";
    echo $callback($name);
}
processUser('greet'); // Output: Hello, User!
  • Anonymous Function Callback: You can use anonymous functions (closures) as callbacks.

$numbers = [1, 2, 3, 4];
$double = array_map(function($n){ 
          return $n * 2; }, $numbers);

print_r($double); 
// Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
  • Callback in Object-Oriented Programming: You can pass a class method as a callback using an array: [$object, 'methodName'].


class Greeter {
    public function greet($name) {
        echo "Hello, " . $name . "!";
    }
}

function processUserMethod($callback) {
    $name = "Alice";
    call_user_func($callback, $name);
}

$greeter = new Greeter();
processUserMethod([$greeter, 'greet']); 
// Outputs: Hello, Alice!

# Using Built-In Functions with Callbacks

PHP has many built-in functions that accept callbacks, such as:

  • array_map() - Applies the callback to each element of an array.
  • call_user_func() - Calls the callback function passed as a string or array.
  • call_user_func_array() - Calls the callback with arguments supplied as an array.

Let's see the example of call_user_func().


function sayHello($name) {
    return "Hello, " . $name . "!";
}
echo call_user_func('sayHello', 'World'); // Output: Hello, World!

Callback functions are a core concept for writing efficient and modular PHP code, making functions highly customizable and dynamic.

# Benefits of using callback function

  • Flexibility: Change behavior of a function without modifying its structure.
  • Reusability: Same logic can be reused with different callbacks.
  • Modularity: Helps separate concerns and create cleaner code.

Share:

Post a Comment (0)
Copyright © 2025 Web Techstack | All rights reserved