函数解释:
call_user_func — 把第一个参数作为回调函数调用 官方文档
call_user_func_array — 调用回调函数,并把一个数组参数作为回调函数的参数 官方文档
代码:
<?php
/**
* 自定义方法test
* @param $a 参数a
* @param $b 参数b
*/
function test($a, $b)
{
echo $a + $b;
}
//字符串传参 //返回结果=3
echo call_user_func('test', 1, 2);
//数组式传参 //返回结果=3
echo call_user_func_array('test', [1, 2]);
/**
* 调用匿名函数
*/
//返回结果=3
echo call_user_func(function ($a, $b) {
echo $a + $b;
}, 1, 2);
//返回结果=3
echo call_user_func_array(function ($a, $b) {
echo $a + $b;
}, [1, 2]);
/**
* 调用系统函数等同于 echo strtoupper('abc');
*/
echo call_user_func('strtoupper', 'abc'); // ABC
echo call_user_func_array('strtoupper', ['abc']); // ABC
/**
* 声明一个类Test
* Class Test
*/
class Test
{
/**
* 静态方法demo
* @param $a
* @param $b
*/
static public function demo($a, $b)
{
echo $a + $b;
}
/**
* 动态方法show
* @param $a
* @param $b
*/
public function show($a, $b)
{
echo $a + $b;
}
}
// 调用类中的静态方法
// 类名方法名以数据形式
echo call_user_func(['Test', 'demo'], 1, 2); // 3
echo call_user_func_array(['Test', 'demo'], [1, 2]); // 3
// 类名方法名以字符串形式
echo call_user_func('Test::demo', 1, 2); // 3
echo call_user_func_array('Test::demo', [1, 2]); // 3
// 调用类中的动态方法,对象和方法必须通过数组形式传递
echo call_user_func([new Test, 'show'], 1, 2); // 3
echo call_user_func_array([new Test, 'show'], [1, 2]); // 3
/**
* 调用redis的方法批量写入有序集合
* 等同于$redis->zAdd('key_name1',100,1,100,2,100,3,100,4,100,5);
*/
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$time_array = array('key_name1',100,1,100,2,100,3,100,4,100,5);
$results = call_user_func_array(array($redis, 'zAdd'), $time_array); //5