In PHP, callback is a function object/reference with type callable. A callback/callable variable can act as a function, object method and a static class method. There are various ways to implement a callback. Some of them are discussed below:
Standard callback: In PHP, functions can be called using call_user_func() function where arguments is the string name of the function to be called.
Example:
<?php
function someFunction() {
echo "Geeksforgeeks \n";
}
call_user_func('someFunction');
?>
|
Static class method callback: Static class methods can be called by using call_user_func() where argument is an array containing the string name of class and the method inside it to be called.
Example:
<?php
class GFG {
static function someFunction() {
echo "Parent Geeksforgeeks \n";
}
}
class Article extends GFG {
static function someFunction() {
echo "Geeksforgeeks Article \n";
}
}
call_user_func(array('Article', 'someFunction'));
call_user_func('Article::someFunction');
call_user_func(array('Article', 'parent::someFunction'));
?>
|
Output:
Geeksforgeeks Article
Geeksforgeeks Article
Parent Geeksforgeeks
Object method callback: Object methods can be called by using call_user_func() where argument is an array containing the object variable and the string name of method to be called. Object method can also be called if they are made invokable using __invoke() function definition. In this case, argument to the call_user_func() function is the object variable itself.
Example:
<?php
class GFG {
static function someFunction() {
echo "Geeksforgeeks \n";
}
public function __invoke() {
echo "invoke Geeksforgeeks \n";
}
}
$obj = new GFG();
call_user_func(array($obj, 'someFunction'));
call_user_func($obj);
?>
|
Output:
Geeksforgeeks
invoke Geeksforgeeks
Closure callback: Closure functions can be made callable by making standard calls or mapping closure function to array of valid arguments given to the closure function using array_map() function where arguments are the closure function and an array of its valid arguments.
Example:
<?php
$print_function = function($string) {
echo $string."\n";
};
$string_array = array("Geeksforgeeks", "GFG", "Article");
array_map($print_function, $string_array);
?>
|
Output:
Geeksforgeeks
GFG
Article
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!