PHP call_user_func() Function
The PHP call_user_func() function is used to call a user defined function or method, with the specified arguments.
Syntax
call_user_func(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 zero or more parameters to be passed to the function. |
Return Value
Returns the function result, or false on error.
Example: call_user_func() example
The example below shows the usage of call_user_func() 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("foobar", "one", "two"); // Call the $foo->bar() method with 2 arguments $obj = new foo; call_user_func(array($obj, "bar"), "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() 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(__NAMESPACE__ .'\Foo::test', 'John'); call_user_func(array(__NAMESPACE__ .'\Foo', 'test'), '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($func, 5, 9)); ?>
The output of the above code will be:
int(45)
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