Create one or more callback
functions and execute them using different built-in methods, user-defined functions and static classes in PHP.
[Create a function in PHP callback
and call_user_func
execute it using
We create a function named testFunction()
and callback
use call_user_func()
the method to execute it by passing the function name as a string to the method.
example:
<?php
function testFunction() {
echo "Testing Callback \n";
}
// Standard callback
call_user_func('testFunction');
?>
Output:
Testing Callback
[Create a function in PHP callback
and array_map
execute it using method]
We use array_map
the method to execute callback
the function. This will execute the method using array_map()
the corresponding data passed to the function.
example:
<?php
function length_callback($item) {
return strlen($item);
}
$strings = ["Kevin Amayi", "Programmer", "Nairobi", "Data Science"];
$lengths = array_map("length_callback", $strings);
print_r($lengths);
?>
Output:
Array ( [0] => 11 [1] => 10 [2] => 7 [3] => 12 )
[Implement multiple callback functions in PHP and execute them using user-defined functions]
We will use testCallBacks()
a user-defined function named to execute two functions named name
and , bypassing the user-defined function with the name of the function as a string.age
callback
example:
<?php
function name($str) {
return $str . " Kevin";
}
function age($str) {
return $str . " Kevin 23 ";
}
function testCallBacks($str, $format) {
// Calling the $format callback function
echo $format($str)."<br>";
}
// Pass "name" and "age" as callback functions to testCallBacks()
testCallBacks(" Hello", "name");
testCallBacks(" Hello", "age");
?>
Output:
Hello Kevin
Hello Kevin 23
static
[Use classes and call_user_func
implement static
methods as functions in PHP callback
]
We will static
create two static
classes using the method and execute call_user_func()
them as using the method callbacks
.
<?php
// Sample Person class
class Person {
static function walking() {
echo "I am moving my feet <br>";
}
}
//child class extends the parent Person class
class Student extends Person {
static function walking() {
echo "student is moving his/her feet <br>";
}
}
// Parent class Static method callbacks
call_user_func(array('Person', 'walking'));
call_user_func('Person::walking');
// Child class Static method callback
call_user_func(array('Student', 'Student::walking'));
?>
Output:
I am moving my feet
I am moving my feet
student is moving his/her feet