Dynamic function calls in PHP for AJAX

In PHP you can have dynamic function calls, that is during execution of your PHP script you can trigger a function call based on certain inputs or conditions which you don’t know before hand.

This can be achieved using the following function in PHP

mixed call_user_func ( callback function [, mixed parameter [, mixed …]] )

Here the callback function is, the name of function you have already defined in your PHP script. The name of the function is in string format. Parameters to your function can be passed through the parameter arguments.

This technique can be very useful, in your ajax based applications, where you have PHP backend script which contains all your functions required to draw/show data in the application. You trigger a function call right from your javascript through a POST variable. Your backend PHP scripts looks for the function to be called in the $_POST variable, and passes the name of the function to be called call_user_funct function.
So instead of writing many if-else conditions you directly ask for function to be called on different situations.

for example i have few functions defined in my php script like the one below

<?php
function getEmployees(){
//function code block
}
function getCompanies(){
//function code block
}

?>

I can call these functions dynamically like this. I would set the POST variable ‘call’ to the name of the function I wish to call while I make AJAX request in javascript to my php backend script. The php backend script in turn would call the requried function.

<?php
$function_to_call = $_POST[‘call’];
if(function_exists($function_to_call)){
call_user_func ($function_to_call);
}
else{
//show error or notify that the requested function doesnot exist.
}
?>

Object methods may also be invoked statically using this function by passing array($objectname, $methodname) to the function parameter. See the example below

<?php
class myclass {var $name= “”;

function __construct($name){
$this->name = $name;
}

function say_hello(){
echo “Hello!”. $this->name .”<br>”;
}

static function say_hello_all(){
echo “hello all!<br>”;
}
}

$classname = “myclass”;

$obj1 = new myclass(“Object1”);

$obj2 = new myclass(“Object2”);

call_user_func(array($classname, ‘say_hello_all’));

call_user_func(array($obj1, ‘say_hello’));

call_user_func(array($obj2, ‘say_hello’));

call_user_func(array($obj1, ‘say_hello’));

?>

There is also a similar function available in php which allows you to call a user function given with an array of parameters

mixed call_user_func_array ( callback function, array param_arr )

Here callback function is the function name you want to call and ‘param_arr’ is a simple array of parameters required by your function.

The above technique, helps to keep our code clean, modular and flexible.