1

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?

1
  • For my usage, I'm writing a model loader. It enables us to load any model and execute it without specifying specific model in the code. Similar to Java's dependency injection. Commented May 20, 2011 at 20:07

2 Answers 2

3

You will need to use call_user_func_array and str_getcsv

call_user_func_array(array($obj, "B"), str_getcsv($params));
Sign up to request clarification or add additional context in comments.

1 Comment

@cfoo Accepting an answer is important as it both rewards posters for solving your problem and informs others that your issue is resolved. For more information, please see meta.stackexchange.com/questions/5234/…
1

You can use the call_user_func_array() function as follows:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.