Home > Article > Backend Development > How to use the php function call_user_func
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
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!