Home  >  Article  >  Backend Development  >  How to use the php function call_user_func

How to use the php function call_user_func

小云云
小云云Original
2018-03-14 10:53:015321browse

I browsed the documentation some time ago and found an interesting PHP function: call_user_func. This article mainly shares with you how to use the PHP function call_user_func. I hope it can help you.

Function function: This function is mainly used to call the function through function name

For example:

function test(){
    echo "hello world\n";
}
$methodName = "test";
call_user_func($methodName);
上面的语句执行后相当于直接调用test(),不过是可以通过函数名来调用函数。同时也可以用这种方法来调用:
1
2
$methodName = "test";
$methodName();

generated The result is the same, and this method will be slightly better in performance than the above method.

In addition to calling functions, you can also call object methods:

class T{
    static public function test(){
        echo "hello world\n";
    }
}
//php 5.3以前需要这样调用
call_user_func("T::test");
//php 5.3以后,可以将class和method传入一个数组再将数组传给call_user_func方法
call_user_func(array("T", "test"));

The above execution effect is the same

call_user_func can also be used with anonymous functions such as:

function call_func(){
    foreach(func_get_args() as $func){
        call_user_func($func);
    }
}
call_func(function(){
    echo "anonymous function\n";
});

The above function can also call multiple functions at the same time.

Related recommendations:

Detailed explanation of usage examples of php functions call_user_func and call_user_func_array

##Summary of call_user_func_array() function definition and usage

php call_user_func function

The above is the detailed content of How to use the php function call_user_func. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn