LibraryThingTim LibraryThingTim - 9 months ago 50
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.


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