A callback function, or simply “callback,” is a function passed as an argument to another function.
Any existing function can serve as a callback. To use a function as a callback, pass its name as a string argument to another function.
Pass a callback to PHP’s array_map()
function to compute the length of each string in an array.
<?php function my_callback($item) { return strlen($item); } $strings = [“apple”, “orange”, “banana”, “coconut”]; $lengths = array_map(“my_callback”, $strings); print_r($lengths); ?> |
User-defined functions and methods can also accept callback functions as arguments. To invoke a callback function within a user-defined function or method, use parentheses with the variable and pass arguments just like with regular functions.
Execute a callback within a user-defined function:
<?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”); ?> |