在 php 中实现回调函数
本文将向你展示如何创建一个或多个 callback 函数并使用 php 中的不同内置方法、用户定义函数和静态类来执行它们。
在 php 中创建一个 callback 函数并使用 call_user_func 执行
我们创建了一个名为 testfunction() 的 callback 函数,并使用 call_user_func() 方法通过将函数名称作为字符串传递给该方法来执行它。
例子:
php
function testfunction() {
echo "testing callback \n";
}
// standard callback
call_user_func('testfunction');
?>
输出:
testing callback
在 php 中创建一个 callback 函数并使用 array_map 方法执行
我们使用 array_map 方法执行 callback 函数。这将使用传递给 array_map() 函数的相应数据执行该方法。
例子:
php
function length_callback($item) {
return strlen($item);
}
$strings = ["kevin amayi", "programmer", "nairobi", "data science"];
$lengths = array_map("length_callback", $strings);
print_r($lengths);
?>
输出:
array ( [0] => 11 [1] => 10 [2] => 7 [3] => 12 )
在 php 中实现多个回调函数并使用用户定义的函数执行它们
我们将使用名为 testcallbacks() 的用户定义函数执行两个名为 name 和 age 的 callback 函数,将函数的名称作为字符串绕过用户定义的函数。
例子:
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)."
";
}
// pass "name" and "age" as callback functions to testcallbacks()
testcallbacks(" hello", "name");
testcallbacks(" hello", "age");
?>
输出:
hello kevin
hello kevin 23
在 php 中使用 static 类和 call_user_func 将 static 方法实现为 callback 函数
我们将使用 static 方法创建两个 static 类,并使用 call_user_func() 方法将它们作为 callbacks 执行。
php
// sample person class
class person {
static function walking() {
echo "i am moving my feet
";
}
}
//child class extends the parent person class
class student extends person {
static function walking() {
echo "student is moving his/her feet
";
}
}
// 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'));
?>
输出:
i am moving my feet
i am moving my feet
student is moving his/her feet
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
如何在 php 中获取时间差的分钟数
发布时间:2023/03/29 浏览次数:204 分类:php
-
本文介绍了如何在 php 中获取时间差的分钟数,包括 date_diff()函数和数学公式。它包括 date_diff()函数和数学公式。
发布时间:2023/03/29 浏览次数:156 分类:php
-
本教程演示了如何将用户从页面重定向到 php 中的其他页面
