PHP Callback Functions


In PHP, a callback function is a function that is passed as an argument to another function. This allows the receiving function to call the passed function dynamically at runtime.

Callbacks are useful for customizing behavior, processing arrays, or executing code dynamically based on user requirements.

What Are Callback Functions?

A callback function is essentially a reference to a function. Instead of executing a function immediately, you can pass it to another function, which can then decide when and how to run it.

Use cases:

  • Sorting arrays using custom comparison logic.

  • Applying transformations to each element of an array.

  • Implementing flexible and reusable code.

Types of Callback Functions in PHP

  1. Named functions – Traditional functions defined using function.

  2. Anonymous functions – Functions without names, also called closures.

  3. Static methods – Class methods used as callbacks.

  4. Object methods – Non-static methods passed as callbacks.

Example 1: Named Function as a Callback

<?php
// Function that takes a callback
function greetUser($callback) {
    echo $callback("Vicky"); // Call the passed function
}

// Named function to pass as callback
function sayHello($name) {
    return "Hello, $name!";
}

// Using the callback
greetUser("sayHello");
?>

Output:

Hello, Vicky!

Explanation:

  • The sayHello function is passed as an argument to greetUser.

  • Inside greetUser, the function is called using $callback("Vicky").

Example 2: Anonymous Function (Closure) as Callback

<?php
// Function accepting a callback
function processName($callback) {
    echo $callback("Sanjana");
}

// Using an anonymous function as a callback
processName(function($name) {
    return "Welcome, $name!";
});
?>

Output:

Welcome, Sanjana!

Explanation:

  • Anonymous functions can be defined inline without a name.

  • Useful for short, one-time tasks without cluttering the code with separate functions.

Example 3: Using array_map with Callback

The array_map function applies a callback to every element of an array.

<?php
$numbers = [1, 2, 3, 4, 5];

// Callback function to double a number
function double($num) {
    return $num * 2;
}

// Apply callback to each element
$doubledNumbers = array_map("double", $numbers);

print_r($doubledNumbers);
?>

Output:

Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )

Explanation:

  • array_map takes the callback double and applies it to each element.

  • Returns a new array with modified values.

You can also use anonymous functions with array_map:

$doubledNumbers = array_map(function($num) {
    return $num * 2;
}, $numbers);

Example 4: Using usort with Callback

The usort function sorts an array using a custom comparison function.

<?php
$fruits = ["apple", "banana", "cherry", "date"];

// Callback function to sort by string length
function sortByLength($a, $b) {
    return strlen($a) - strlen($b);
}

// Sort the array
usort($fruits, "sortByLength");

print_r($fruits);
?>

Output:

Array ( [0] => date [1] => apple [2] => banana [3] => cherry )

Explanation:

  • usort calls the callback sortByLength for each pair of elements.

  • Sorting logic is customizable via the callback.

Example 5: Using Object Methods as Callbacks

You can also use object methods as callbacks.

<?php
class Greeter {
    public function greet($name) {
        return "Hello, $name!";
    }
}

$greeter = new Greeter();

// Passing object method as callback
function welcomeUser($callback) {
    echo call_user_func($callback, "Amit");
}

// Using array notation for object method
welcomeUser([$greeter, "greet"]);
?>

Output:

Hello, Amit!

Explanation:

  • Object methods are passed as arrays: [object, "methodName"].

  • call_user_func executes the callback dynamically.

Example 6: Using Static Methods as Callbacks

<?php
class MathOperations {
    public static function square($num) {
        return $num * $num;
    }
}

$numbers = [1, 2, 3, 4];

// Using static method as callback
$squaredNumbers = array_map(["MathOperations", "square"], $numbers);

print_r($squaredNumbers);
?>

Output:

Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )

Explanation:

  • Static methods can be referenced with class name and method name.

  • Combined with array_map, they allow efficient array transformations.

Benefits of Callback Functions

  1. Flexibility: Change behavior dynamically without modifying the main function.

  2. Reusability: Functions can work with different callbacks for different tasks.

  3. Cleaner code: Avoid repetitive loops or conditionals.

  4. Integration with built-in functions: Many PHP array functions rely on callbacks (array_map, array_filter, usort, etc.).

Real-World Examples of Callbacks

  • Filtering arrays dynamically using array_filter.

  • Sorting data using usort or uasort.

  • Applying transformations to API data or JSON arrays.

  • Event handling in custom frameworks.

  • Middleware logic in PHP-based applications.

Common Functions That Accept Callbacks

  • array_map → Apply a callback to each array element.

  • array_filter → Keep elements based on a callback condition.

  • usort → Custom sorting logic.

  • uasort → Sort associative arrays with a callback.

  • call_user_func → Call a function dynamically.

  • call_user_func_array → Call a function with multiple parameters.

Best Practices

  1. Prefer anonymous functions for simple, one-time callbacks.

  2. Use named functions for reusable logic.

  3. Ensure callbacks are callable before passing (is_callable() can help).

  4. Keep callbacks lightweight to avoid performance issues in loops.

  5. Combine callbacks with array functions for cleaner, functional-style code.

Summary of the Tutorial

  • Callback functions are functions passed as arguments to other functions.

  • They provide flexibility, reusability, and dynamic execution.

  • PHP supports named functions, anonymous functions, object methods, and static methods as callbacks.

  • Many built-in functions like array_map, array_filter, and usort rely on callbacks.

  • Mastering callbacks helps create modular, efficient, and dynamic PHP applications.


Practice Questions

  1. Write a PHP named function that takes a number and returns its square, then pass it as a callback to array_map for an array of numbers.

  2. Create a PHP anonymous function as a callback to convert all strings in an array to uppercase using array_map.

  3. Write a PHP function that filters an array of numbers to keep only even numbers using array_filter and a callback.

  4. Create a PHP callback function to sort an array of strings by length using usort.

  5. Write a PHP class with a static method that doubles a number, then use it as a callback in array_map.

  6. Create a PHP object method that greets a user, and call it dynamically using call_user_func.

  7. Write a PHP anonymous function as a callback that adds 10 to each element of an array using array_map.

  8. Create a PHP callback function that checks if a string starts with a specific letter, and use it with array_filter.

  9. Write a PHP function that takes another function as a parameter and applies it to a number to return the result.

  10. Create a PHP callback that calculates the factorial of a number and use it to process an array of integers.


Go Back Top