PHP Callback Functions

In PHP, callback functions are functions that can be passed as arguments to other functions and invoked later. They are useful for implementing dynamic behavior, especially in functions like array manipulation (array_map, array_filter, usort, etc.).


Types of Callback Functions in PHP

  1. Simple Function Name

    function sayHello($name) { return "Hello, $name!"; } echo call_user_func("sayHello", "John");
  2. Anonymous Function (Closure)

    $greet = function($name) { return "Hi, $name!"; }; echo call_user_func($greet, "Jane");
  3. Static Class Method

    class MyClass { public static function sayHi($name) { return "Hi from static, $name!"; } } echo call_user_func(["MyClass", "sayHi"], "Tom");
  4. Object Method

    class Greeter { public function greet($name) { return "Hello from object, $name!"; } } $obj = new Greeter(); echo call_user_func([$obj, "greet"], "Lisa");

Common Functions Using Callbacks

  • array_map

    $numbers = [1, 2, 3]; $squared = array_map(function($n) { return $n * $n; }, $numbers); print_r($squared);
  • array_filter

    $values = [1, 2, 3, 4]; $even = array_filter($values, function($n) { return $n % 2 == 0; }); print_r($even);
  • usort

    $arr = [3, 1, 4, 2]; usort($arr, function($a, $b) { return $a - $b; }); print_r($arr);

Why Use Callbacks?

  • Decouple logic from implementation.

  • Enable functional-style programming.

  • Promote code reuse and flexibility.