PHP: Variable in a function name

Viewed 24563

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.

8 Answers

For PHP >= 7 you can use this way:

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

$animal = 'cow';
print ("sound_$animal")();

And yet another solution to what I like to call the dog-cow problem. This will spare a lot of superfluous function names and definitions and is perfect PHP syntax and probably future proof:

$animal = 'cow';
$sounds = [
    'dog' => function() { return 'woof'; },
    'cow' => function() { return 'moo'; }
];

print ($sounds[$animal])();

and looks a little bit less like trickery as the "string to function names" versions.

JavaScript devs might prefer this one for obvious reasons.

(tested on Windows, PHP 7.4.0 Apache 2.4)

Related