PHP: Variable in a function name

后端 未结 7 1885
有刺的猬
有刺的猬 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:36

    You can do it like this:

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

    However, a much better way would be to use an array:

    $sounds = array('dog' => sound_dog, 'cow' => sound_cow);
    
    $animal = 'cow';
    print $sounds[$animal]();
    

    One of the advantages of the array method is that when you come back to your code six months later and wonder "gee, where is this sound_cow function used?" you can answer that question with a simple text search instead of having to follow all the logic that creates variable function names on the fly.

提交回复
热议问题