LibraryThingTim LibraryThingTim - 1 year ago 82
PHP Question

PHP: Variable in a function name

I want to trigger a function based on a variable.

function sound_dog() { return 'woof'; }
function sound_cow() { return 'moo'; }

$animal = 'cow';
print sound_{$animal}(); *

The * line is the line that's not correct.

I've done this before, but I can't find it. I'm aware of the potential security problems, etc.

Anyone? Many thanks.

Answer Source

You can do that, but not without interpolating the string first:

$animfunc = 'sound_' . $animal;
print $animfunc();

Or, skip the temporary variable with call_user_func():

call_user_func('sound_' . $animal);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download