PHP Callback Functions

This tutorial helps you learn how to use PHP Call back Function. Let's first see what are PHP Callback Functions.

 

What is PHP Callback Function?

It is a function that is passed as an argument into another function.

You can use any existing function as a callback function. For using a function as a callback function, you need to pass a string containing the function's name as the argument of another function.

<?php
function my_callback($item) {
  return strlen($item);
}

$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map("my_callback", $strings);
print_r($lengths);
?>

 

Callbacks in User Defined Functions

User-defined functions also take callback functions as arguments. For using callback functions within a user-defined function, you can call it by adding parentheses to the variable and pass arguments as with normal functions:

<?php
function exclaim($str) {
  return $str . "! ";
}

function ask($str) {
  return $str . "? ";
}

function printFormatted($str, $format) {
  // Calling the $format callback function
  echo $format($str);
}

// Pass "exclaim" and "ask" as callback functions to printFormatted()
printFormatted("Hello world", "exclaim");
printFormatted("Hello world", "ask");
?>