PHP: Variable in a function name

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

    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);
    
    0 讨论(0)
提交回复
热议问题