PHP: Variable in a function name

后端 未结 7 1889
有刺的猬
有刺的猬 2020-12-09 16:57

I want to trigger a function based on a variable.

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

$animal = \'cow\';
print soun         


        
7条回答
  •  清歌不尽
    2020-12-09 17:28

    http://php.net/manual/en/functions.variable-functions.php

    To do your example, you'd do

    $animal_function = "sound_$animal";
    $animal_function();
    

提交回复
热议问题