call_user_func_array & call_user_func

call_user_func_array

说明

mixed call_user_func_array ( callable $callback , array $param_arr )
调用回调函数,并把一个数组参数作为回调函数的参数

和匿名函数使用

call_user_func_array(function ($name, $age) {
    echo "$name is $age now";
}, ['Zoe', 29]);

// Output:
// Zoe is 29

和函数一起

function showAge($name, $age)
{
    echo "$name is $age now";
}

call_user_func_array('showAge', ['Zoe', 29]);

// Output:
// Zoe is 29

和类一起,静态

class Test {
    private static function showAge($name, $age)
    {
        echo "$name is $age now";
    }

    public static function userFunc()
    {
        call_user_func_array(['self', 'showAge'], ['David', 36]);
    }
}
Test::userFunc();

// Output:
// David is 36

和类一起

class Test {
    private function showAge($name, $age)
    {
        echo "$name is $age now";
    }

    public function userFunc()
    {
        call_user_func_array([$this, 'showAge'], ['David', 36]);
    }
}

$classTest = new Test();
$classTest->userFunc();

// Output:
// David is 36

call_user_func

说明

mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )
第一个参数 callback 是被调用的回调函数,其余参数是回调函数的参数,传入 call_user_func() 的参数不能为引用传递。

和匿名函数一起

call_user_func(function ($name, $age) {
    echo "$name is $age now";
}, 'Peter', 20);

// Output:
// Peter is 20 now

和函数一起

function showAge($name, $age)
{
    echo "$name is $age now";
}
call_user_func('showAge', 'Bill', 45);

// Output:
// Bill is 45 now

和类一起

class Test
{
    public function showAge($name, $age)
    {
        echo "$name is $age now";
    }
}
$classTest = new Test();
call_user_func([$classTest, 'showAge'], 'Eve', 29);

// Output:
// Eve is 29 now


class Test
{
    public function showAge($name, $age)
    {
        echo "$name is $age now";
    }

    public function useFunc()
    {
        call_user_func([$this, 'showAge'], 'Lisa', 19);
    }
}
$classTest = new Test();
$classTest->useFunc();

// Output:
// Lisa is 19 now

和类一起,静态

class Test {
    public static function showAge($name, $age)
    {
        echo "$name is $age now";
    }

    public static function userFunc()
    {
        call_user_func(['self', 'showAge'], 'David', 36);
    }
}
Test::userFunc();

// Output:
// David is 36 now

你可能感兴趣的:(call_user_func_array & call_user_func)