Callback in PHP, is a function which is passed to another function as an argument, This function executes the callback function as needed. Callback function can be a
- Regular PHP user-defined function
- In-built function.
- Object methods
- Static class methods
- anonymous functions
- Arrow functions
- Language constructs should not be used as callbacks like array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().
Callback function should be passed as string in argument to another function.
<?php
// Callback function
function myCallback($language) {
echo "Callback function says Hello From " . $language;
}
// Regular function
function SendName($callback) {
$myCallback("PHP");
}
//calling regular function with callback function as argument
SendName("myCallback");
?>
Anonymous function (Closures)
<?php
// Anonymous function example
$myCallback = function ($language) {
echo "Anonymous function says Hello From : $language";
};
// Using the anonymous function
$myCallback("PHP");
?>