PHP:函数名称中的变量 [英] PHP: Variable in a function name
本文介绍了PHP:函数名称中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想基于变量触发功能.
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.
有人吗?非常感谢.
推荐答案
您可以做到这一点,但必须先对字符串进行插值:
You can do that, but not without interpolating the string first:
$animfunc = 'sound_' . $animal;
print $animfunc();
或者,使用 call_user_func()跳过临时变量:
Or, skip the temporary variable with call_user_func():
call_user_func('sound_' . $animal);
这篇关于PHP:函数名称中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文