Asim Zaidi
Asim Zaidi

Reputation: 28284

getting function name dynamically

I need to get my function name called dynamically.

$myFunction = isset($somecondition) ? "function1(100,100)" : "function(300,300)";

then I need to call the method

$myclass->$myFunction;

Upvotes: 0

Views: 92

Answers (3)

remy
remy

Reputation: 1501

You are searching the call_user_func_array method

call_user_func_array(
    array($myClass, isset($somecondition) ? 'function1' : 'function'), 
    isset($somecondition) ? array(100, 100) : array(300, 300)
);

it is not possible to name a function function, so there are a lot more problems with his code ;)

Upvotes: 1

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

You can not store the function call in a string like that. You could store the function name and the parameters separately, but you would probably just be better off using a simple if statement and calling either method with the specific parameters.

if($someCondition){
    $myClass->function1(100, 100);
} else {
    $myClass->function(300, 300);
}

any other way would either be storing the function name and parameters in a variable and using user_call_func_array(), but you would still need an if statement like above or the other option is to use two ternary statements like in remy's answer just with another ternary to switch between function1 and function. This method is less than ideal simply because you are processing two ternary statements instead of just one with the if statement above.

Upvotes: 2

Ibu
Ibu

Reputation: 43810

The parentheses are missinng

$myclass->$myFunction();

Upvotes: -2

Related Questions