call_user_func
Description
The call_user_func of Function Handling for PHP call the callback given by the first parameter.
Syntax
call_user_func(
callable $callback,
mixed ...$args
): mixedParameters
callback
The callable to be called.
args
Zero or more parameters to be passed to the callback.
NOTE: Note that the parameters for call_user_func() are not passed by reference.
Return
Returns the return value of the callback.
Examples
1 · callback
<?
function myfunction()
{
return __FUNCTION__ . " Hello World!";
}
$callback = "myfunction";
$return = call_user_func($callback);
echo $return;
myfunction Hello World!
2 · args
<?
function myfunction($myparameter1, $myparameter2)
{
return __FUNCTION__ . " $myparameter1 $myparameter2";
}
$callback = "myfunction";
$arg1 = "Hello";
$arg2 = "World!";
$return = call_user_func($callback, $arg1, $arg2);
echo $return;
myfunction Hello World!
3 · closure
<?
$myfunction = function($myparameter1, $myparameter2)
{
return __FUNCTION__ . " $myparameter1 $myparameter2";
};
$callback = $myfunction;
$arg1 = "Hello";
$arg2 = "World!";
$return = call_user_func($callback, $arg1, $arg2);
echo $return;
{closure:/home/osbocom/public_html/php/demo/index.php:3} Hello World!4 · class
<?
class myclass
{
static function myfunction($myparameter1, $myparameter2)
{
return __METHOD__ . " $myparameter1 $myparameter2";
}
}
$callback = "myclass::myfunction";
$arg1 = "Hello";
$arg2 = "World!";
$return = call_user_func($callback, $arg1, $arg2);
echo $return;
myclass::myfunction Hello World!
5 · class
<?
class myclass
{
static function myfunction($myparameter1, $myparameter2)
{
return __METHOD__ . " $myparameter1 $myparameter2";
}
}
$callback = ["myclass", "myfunction"];
$arg1 = "Hello";
$arg2 = "World!";
$return = call_user_func($callback, $arg1, $arg2);
echo $return;
myclass::myfunction Hello World!
6 · class
<?
class myclass
{
static function myfunction($myparameter1, $myparameter2)
{
return __METHOD__ . " $myparameter1 $myparameter2";
}
}
$callback = [new myclass(), "myfunction"];
$arg1 = "Hello";
$arg2 = "World!";
$return = call_user_func($callback, $arg1, $arg2);
echo $return;
myclass::myfunction Hello World!
7 · namespace
<?
namespace mynamespace;
class myclass
{
static function myfunction($myparameter1, $myparameter2)
{
return __NAMESPACE__ . " $myparameter1 $myparameter2";
}
}
$callback = __NAMESPACE__ . "\myclass::myfunction";
$arg1 = "Hello";
$arg2 = "World!";
$return = call_user_func($callback, $arg1, $arg2);
echo $return;
mynamespace Hello World!
8 · namespace
<?
namespace mynamespace;
class myclass
{
static function myfunction($myparameter1, $myparameter2)
{
return __NAMESPACE__ . " $myparameter1 $myparameter2";
}
}
$callback = [__NAMESPACE__ . "\myclass", "myfunction"];
$arg1 = "Hello";
$arg2 = "World!";
$return = call_user_func($callback, $arg1, $arg2);
echo $return;
mynamespace Hello World!