cfoo
cfoo

Reputation: 73

PHP function parameters from a string

How do I make a truely dynamic function with dynamic parameters call? The documentation and examples I've found all assume you have only 1 parameter. I would like to have multiple parameters, example:

class Object {
    function A($p1) {}
    function B($p1,$p2) {}
}

$obj = new Object();
$function = "B";
$params = "'foo', 'me'";

$obj->$function($params);

calling $function = "A" will be fine as $params is treated as a string. I've tried

$obj->$function(explode(',',$params));

for $function="B" but it does not work as explode simply returns an array and thus function B has a missing parameter.

Any idea?

Upvotes: 1

Views: 2385

Answers (2)

Nick
Nick

Reputation: 6965

You can use the call_user_func_array() function as follows:

call_user_func_array(array($obj, $function), explode(',', $params));

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163318

You will need to use call_user_func_array and str_getcsv

call_user_func_array(array($obj, "B"), str_getcsv($params));

Upvotes: 3

Related Questions