Kermit the Frog
Kermit the Frog

Reputation: 3969

Variables method names for classes

How can I call a function in a class that depends on a user's input.

So if the user sent 2011 I want to call the method $record->show_2011()

if they sent the input 2012 I want to call the method $record->show_2012()

else I want to call $record->show()

How do I pass in the user's input into the method name to call it?

Upvotes: 0

Views: 71

Answers (3)

marekful
marekful

Reputation: 15351

You can also do it this way:

$record->{'show'}();

$record->{'show_' . $variableThatHoldsTheRestOfFunctionName}();

Upvotes: 0

Lauri Elias
Lauri Elias

Reputation: 1299

You need to put the function name in a variable first, e.g. $function_name = 'set'.$request->getFirstProperty(); and then $record->$function_name();

Upvotes: 0

Matthew
Matthew

Reputation: 11260

$functionToCall = 'show_' . $userInput;
$record->$functionToCall();

Upvotes: 2

Related Questions