回调函数顾名思义, 就是函数内部使用另外一个函数。使用回调函数也很简单, 我们可以通过2个方法实现:
一:使用变量函数
function test($a){
return $a();
}
function demo(){
return 'A';
}
echo test('demo'); //输出demo函数返回的值即: A
二:使用函数call_user_func_array()
该函数是php的内置函数, 需要传入2个参数, 第一个是要调用的函数名, 第二个是参数列表(数组形式), 函数会将第二个参数中的参数按顺序依次传入调用的函数的参数中。
function test($a){
return call_user_func_array($a,array());
}
function demo(){
return 'A';
}
echo test('demo'); //输出demo函数返回的值即: A
上诉2种方法都是在全局函数中使用回调函数, 那么如果是类中的方法该如何进行回调呢? 也很简单我们依旧借助call_user_func_array()函数
call_user_func_array(array(对象引用,"类中的方法名称字符串"),传递给此方法的参数(数组形式)) // 调用类中的方法
call_user_func_array(array("类名称字符串","类中的静态方法名称字符串"),传递给此方法的参数(数组形式)) // 调用类中的静态方法
// 例一: 调用类中的成员方法
class learn{
function demo(){
return 'A';
}
}
function test(){
return call_user_func_array(array(new learn(),'demo'),array());
}
echo test(); //调用类learn中的方法demo, 输出A
// 例二: 调用类中的静态成员方法
class learn{
static function demo(){
return 'A';
}
}
function test(){
return call_user_func_array(array('learn','demo'),array());
}
echo test(); //调用类learn中的方法demo, 输出A
来源:CSDN
作者:zeros:
链接:https://blog.csdn.net/weixin_46193778/article/details/103989266