call_user_func,call_user_func_array,is_callback

新建一个类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Test
{
public $name = 'name';

public function index()
{
return 'normal function' .$this->name;
}

public static function index2()
{
return 'static function';
}

public static function index3()
{
return function (){};
}
}
is_callback($callback)

注:判断是否为回调函数

1
2
3
4
5
6
7
8
//对象调用
is_callback([new Test(),'index']); 返回 true
//类调用
is_callback(['Test','index2]); 返回 true
//命名空间调用
is_callback('Test::index'); 返回 ture
//直接回调函数
is_callback(Test::index3()); 返回 ture
call_user_func($callback,$arg1,$arg2);

注:调用回调函数
返回:回调函数返回的结果

1
2
3
4
5
6
7
8
9
//对象调用
call_user_func([new Test(),'index'])
//类调用
call_user_func(['Test','index']);
//命名空间调用(不建议使用)
call_user_func('Test::index');
这种方法弱index是静态方法没问题,不是静态方法可能报错,本文的事例代码调用会报错
//直接调用回调函数
call_user_function(Test::index3());
call_user_func_array($callback,array($arg1,$arg2));

注:调用回调函数,参数为数组,$arg1为回调函数的第一个参数,$arg2为第二个,以此类推
返回:回调函数返回的结果

1
2
3
4
5
6
7
8
9
//对象调用
call_user_func([new Test(),'index'],array($arg1,$arg2))
//类调用
call_user_func(['Test','index'],array($arg1,$arg2));
//命名空间调用(不建议使用)
call_user_func('Test::index',array($arg1,$arg2));
这种方法弱index是静态方法没问题,不是静态方法可能报错,本文的事例代码调用会报错
//直接调用回调函数
call_user_function(Test::index3(),array($arg1,$arg2));