PHP内置函数array_reverse、array_reduce、call_user_func和call_user_func_array

来源:互联网 发布:程序最小公倍数算法 编辑:程序博客网 时间:2024/06/05 03:12

1、array_reverse()函数比较简单,倒置数组:

$pipes = [    'Pipe1',    'Pipe2',    'Pipe3',    'Pipe4',    'Pipe5',    'Pipe6',];$pipes = array_reverse($pipes);var_dump($pipes);// outputarray(6) {  [0] =>  string(5) "Pipe6"  [1] =>  string(5) "Pipe5"  [2] =>  string(5) "Pipe4"  [3] =>  string(5) "Pipe3"  [4] =>  string(5) "Pipe2"  [5] =>  string(5) "Pipe1"}
2、array_reduce内置函数主要是用回调函数去迭代数组中每一个值,并且每一次回调得到的结果值作为下一次回调的初始值,最后返回最终迭代的值:

/** * @link http://php.net/manual/zh/function.array-reduce.php * @param int $v * @param int $w * * @return int */function rsum($v, $w){    $v += $w;    return $v;}$a = [1, 2, 3, 4, 5];// 10为初始值$b = array_reduce($a, "rsum", 10);// 最后输出 (((((10 + 1) + 2) + 3) + 4) + 5) = 25echo $b . PHP_EOL; 

3、call_user_func()是执行回调函数,并可输入参数作为回调函数的参数,看测试代码:

class TestCallUserFunc{    public function index($request)    {        echo $request . PHP_EOL;    }}   /** * @param $test */function testCallUserFunc($test){    echo $test . PHP_EOL;}// [$class, $method]call_user_func(['TestCallUserFunc', 'index'], 'pipes'); // 输出'pipes'// Closurecall_user_func(function ($passable) {    echo $passable . PHP_EOL;}, 'pipes'); // 输出'pipes'// functioncall_user_func('testCallUserFunc' , 'pipes'); // 输出'pipes'
4、call_user_func_array与call_user_func基本一样,只不过传入的参数是数组:

class TestCallUserFuncArray{    public function index($request)    {        echo $request . PHP_EOL;    }}/** * @param $test */function testCallUserFuncArray($test){    echo $test . PHP_EOL;}// [$class, $method]call_user_func_array(['TestCallUserFuncArray', 'index'], ['pipes']); // 输出'pipes'// Closurecall_user_func_array(function ($passable) {    echo $passable . PHP_EOL;}, ['pipes']); // 输出'pipes'// functioncall_user_func_array('testCallUserFuncArray' , ['pipes']); // 输出'pipes'

0 0