在PHP中,假设您有如下代码:
$infrastructure = mt_rand(0,100);
if ($infrastructure < $min_infrastructure) $infrastructure = $min_infrastructure;
//do some other stuff with $infrastructure
$country->set_infrastructure($infrastructure);
$education = mt_rand(0,100);
if ($education < $min_education) $education = $min_education;
//do some other stuff with $education
$country->set_education($education);
$healthcare = mt_rand(0,100);
if ($healthcare < $min_healthcare) $healthcare = $min_healthcare;
//do some other stuff with $healthcare
$country->set_healthcare($healthcare);是否有办法将这些类似的指令组合成一个可以称为:
change_stats("infrastructure");
change_stats("education");
change_stats("healthcare");基本上,中的变量可以在其他变量名和函数名中使用吗?
提前谢谢。
发布于 2009-10-24 13:25:53
您可以使用PHP所称的“可变变量”来完成此操作。我希望您的示例是人为的,因为它看起来有点奇怪,但是假设变量和对象是全局的,您可以这样编写name_pet()函数:
function name_pet($type, $name)
{
$class='the_'.$type;
$var=$type.'_name';
$GLOBALS[$class]->setName($name);
$GLOBALS[$var]=$name;
}编辑:这个答案指的是问题的早期版本。
发布于 2009-10-24 13:15:28
我不确定这个函数,但是您可以使用__set做类似的事情
$data;
function __set($key, $val) {
$this->data["$key"] = $val;
}是的,您可以动态使用变量。
$foo = "bar";
$dynamic = "foo";
echo $$dynamic; //would output bar
echo $dynamic; //would output foo发布于 2009-10-24 13:16:21
是的,这是可能的,看看这里的讨论和这里的教程。
https://stackoverflow.com/questions/1617976
复制相似问题