Callback Functions
A callback function, which is often just called \”callback,\” is a function that is passed to another function as an argument.
A callback function can be any function that is already in use. To use a function as a callback function, you must pass the function\’s name as an argument to another function:
Example
Give PHP\’s array map() function a callback to figure out how long each string in an array is:
<!DOCTYPE html>
<html>
<body><?php
function my_callback($item) {
return strlen($item);
}$colors = [\”Red\”, \”Green\”, \”Blue\”, \”Black\”];
$lengths = array_map(\”my_callback\”, $colors);
print_r($lengths);
?></body>
</html>
Output
Array ( [0] => 3 [1] => 5 [2] => 4 [3] => 5 )
Example 2
As of PHP version 7, anonymous functions can be passed as callback functions:
<!DOCTYPE html>
<html>
<body><?php
$colors = [\”Red\”, \”Orange\”, \”Yellow\”, \”Pink\”];
$lengths = array_map( function($item) { return strlen($item); } , $colors);
print_r($lengths);
?></body>
</html>
Output
Array ( [0] => 3 [1] => 6 [2] => 6 [3] => 4 )
User Defined Functions callbacks.
Callback functions can also be passed as arguments to user-defined functions and methods. To use callback functions inside a user-defined function or method, add parentheses around the variable and pass arguments as you would with regular functions:
Example
Use a user-defined function to run a callback:
<!DOCTYPE html>
<html>
<body><?php
function mark($var) {
return $var . \”! \”;
}function ask($var) {
return $var . \”? \”;
}function wordmark($var, $mark) {
// Calling the $mark callback function
echo $mark($var);
}// Pass \”mark\” and \”ask\” as callback functions to wordmark()
wordmark(\”Loream ipsum\”, \”mark\”);
wordmark(\”Loream ipsum\”, \”ask\”);
?></body>
</html>