Call a function dynamically in php

Rakesh Sharma      No Comments  

How to Call a function dynamically in php using call_user_func()

Call a function dynamically in php

To call a function in php basically we use function or method name to call. like functionname(), But there is different way to Call a function dynamically in php. Like we want to call class method or function with a variable or in loop. Today we’ll look be some example of Call a function dynamically in php. In php there is a function call_user_func. Which make this simple. This function exist since php 4 to till.

call_user_func() :- Calls the callback given by the first parameter and passes the remaining parameters as arguments.

syntax :-

call_user_func(callable $callback , $parameter1, $parameter2,...);

For more about this function follow manual. Let’s see some of working example of dynamic function call in php.

Call a single function through variable:-

// Decalre a variable and setting up value as function name to call. 
$myfunc ="my_function_name";

//calling the function through variable directly.

//calling the function through call_user_func().

Call a class function dynamically:-

//intiating the class with function.
Class myClass { 
  public function myfunc() { 
    return "Hii i am called"; 
//calling the class function. 
$function = "myfunc"; 
$myobj = new Record; 
call_user_func(array($myobj, $function));

Call function dynamically using loop:- In this example we making two functions and call these function in loop dynamically with array index name.

//Setting up an array to call functions dynamically in loop
$callfunctions = array('func1' => 'func1', 'func2' => 'func2');
foreach($callfunctions as $k=>$v){
  // $param is option to pass.
  call_user_func('get_'.$v.'_call',$param1, $param2);

//Declaring the functions with parameter.
function get_func1_call($param1, $param2){
function get_func2_call($param1, $param2){

Now you are ready to call a function or method dynamically in php, through variable, in loop and a class method.