PHP call_user_func_array() Function
The PHP call_user_func_array() function is used to call a user defined function or method, with the specified arguments.
Syntax
call_user_func_array(callback, args)
Parameters
callback |
Required. Specify the function or method to be called. It can be an array, with the name of the class, and the method, or a string, with a function name. |
args |
Required. Specify one parameter, gathering all the method or function parameters in an array. |
Return Value
Returns the function result, or false on error.
Example: call_user_func_array() example
The example below shows the usage of call_user_func_array() function.
<?php //defining a class with method class foo { public function bar($arg1, $arg2) { echo __METHOD__." got $arg1 and $arg2 \n"; } } //defining a function function foobar($arg1, $arg2) { echo __FUNCTION__." got $arg1 and $arg2 \n"; } //calling the foobar() function with 2 arguments call_user_func_array("foobar", array("one", "two")); // Call the $foo->bar() method with 2 arguments $obj = new foo; call_user_func_array(array($obj, "bar"), array("three", "four")); ?>
The output of the above code will be:
foobar got one and two foo::bar got three and four
Example: call_user_func_array() using namespace name
Consider the example below where describes how to use this function with namespace name.
<?php namespace Foobar; class Foo { static public function test($name) { print "Hello {$name}!\n"; } } call_user_func_array(__NAMESPACE__ .'\Foo::test', array('John')); call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Marry')); ?>
The output of the above code will be:
Hello John! Hello Marry!
Example: using lambda function
The example below describes how to use this function with a lambda function.
<?php $func = function($arg1, $arg2) { return $arg1 * $arg2; }; var_dump(call_user_func_array($func, array(5, 9))); ?>
The output of the above code will be:
int(45)
Example: passing values by reference
When the variable is passed by reference, its value gets changed. Consider the example below:
<?php function myfunc(&$x){ $x = 100; echo "function myfunc \$x=$x\n"; } $var = 500; call_user_func_array('myfunc',array(&$var)); echo "global \$var=$var\n"; ?>
The output of the above code will be:
function myfunc $x=100 global $var=100
Note: Callbacks registered with functions such as call_user_func() and call_user_func_array() will not be called if there is an uncaught exception thrown in a previous callback.
❮ PHP Function Handling Reference