i

PHP Tutorial

Dynamic Function Calls

Dynamic function calls in php mean you can pass the function name to a variable, and the variable will act as a function dynamically. And you can call the variable as function whenever you want the function to be executed.  

For example, The below code will also give the same result as 20, and the variable $product acts like a function.

function Multiply($num1, $num2)

{

           $result=$num1 * $num2 ;

           return $result;

}

$product = “Multiply”;

$product(4,5);

echo “ The result is $product”;

?>

We can also call a function inside a function, and the parameter of the second function will behave like a function itself. It is dynamic calling a function through function.

function square($num)

{

           echo $num*$num;

}

function caller($num1, $num2)

{

           $num1($num2);

}

caller(‘square’,5);

?>

In the above example, the output will be 25. The caller function accepts two parameters, and we have given $num1 as a function, i.e. square. So, it dynamically calls the function inside a function and returns the square of $num2, i.e. 5.