I am looking for something similar to the solution here >> Call function from string stored in a variable, however with one difference :
I would like to pass a parameter as well.
For example :
function foo($myvar) {
}
$function = 'foo';
$values = Array('myvar'=>1, 'myvar2'=>2);
if(function_exists($function)) {
// call the function using $function,
// and pass the value $values -- aka $function($values)
}
Any workable solution would be greatly appreciated. Ideally, I would like to use it with classes as follows :
class bar {
function foo($myvar) {
}
}
$function = 'foo';
$values = Array('myvar'=>1, 'myvar2'=>2);
if(function_exists($function)) {
// call the function using $function,
// and pass the value $values -- aka $bar::$function($values)
}
You can call a function on an object passing params, using variables, as follows:
$myBar = new bar(); // usually class names have uppercase first letters though
$myClassname = 'bar';
call_user_func(array($myBar, $function), $values); // method on object
call_user_func(array($myClassname, $function), $values); // class (static) method
call_user_func($myClassname.'::'.$function); // PHP 5.2.3 and higher
// if you had another function $function2 whose args were a list of parameters instead of an array:
call_user_func($myBar, $function2, $param1, $param2, $param3);
More info and examples at http://us1.php.net/call_user_func
Does this helps ?
function process_function($function_param){
$function_param = explode("|",$function_param);
if(function_exists($function_param[0])) {
call_user_func_array($function_param[0],$function_param[1]);
}
}
I think you are looking for method_exist()
which would check if object has particular method.
Here is your solution.
class bar {
function foo($myarr){
foreach($myarr as $val){
echo $val ."<br />" ;
//prints 1 and 2
}
}
}
$myfunc = new bar(); //creating object
$values = Array('myvar'=>1, 'myvar2'=>2);
//checking object has method foo
if(method_exists($myfunc, 'foo')) {
$myfunc->foo($values);
}