PHP | call_user_func() Function

The call_user_func() is an inbuilt function in PHP which is used to call the callback given by the first parameter and passes the remaining parameters as argument. It is used to call the user-defined functions.

Syntax:

mixed call_user_func ( $function_name[, mixed $value1[, mixed $... ]])

Here, mixed indicates that a parameter may accept multiple types.
Parameter: The call_user_func() function accepts two types of parameters as mentioned above and described below:



  • $function_name: It is the name of function call in the list of defined function. It is a string type parameter.
  • $value: It is mixed value. One or more parameters to be passed to the function.

Return Value: This function returns the value returned by the callback function.

Below programs illustrate the call_user_func() function in PHP:

Program 1: Call the function

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
function GFG($value)
{
    echo "This is $value site.\n";
}
  
call_user_func('GFG', "GeeksforGeeks");
call_user_func('GFG', "Content");
  
?>

chevron_right


Output:

This is GeeksforGeeks site.
This is Content site.

Program 2: call_user_func() using namespace name

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
namespace Geeks;
  
class GFG {
    static public function demo() {
        print "GeeksForGeeks\n";
    }
}
  
call_user_func(__NAMESPACE__ .'\GFG::demo'); 
  
// Another way of declaration
call_user_func(array(__NAMESPACE__ .'\GFG', 'demo')); 
  
?>

chevron_right


Output:

GeeksForGeeks
GeeksForGeeks

Program 3: Using a class method with call_user_func()

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
class GFG {
    static function show()
    {
        echo "Geeks\n";
    }
}
  
$classname = "GFG";
call_user_func($classname .'::show');
  
// Another way to use object
$obj = new GFG();
call_user_func(array($obj, 'show'));
  
?>

chevron_right


Output:

Geeks
Geeks

Program 4: Using lambda function with call_user_func()

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
call_user_func(function($arg) { print "$arg\n"; }, 'GeeksforGeeks');
?>

chevron_right


Output:

GeeksforGeeks

References: http://php.net/manual/en/function.call-user-func.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.