0

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;

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 ;)

1 Comment

this is the closest answer, but one small thing, the $functionName changes based on $someCondition also. In the end he would probably just be better off doing one if statement and calling either function with the arguments based on that.
-2

The parentheses are missinng

$myclass->$myFunction();

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.