首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP中的变量函数和变量名

PHP中的变量函数和变量名
EN

Stack Overflow用户
提问于 2009-10-24 13:10:40
回答 4查看 298关注 0票数 1

在PHP中,假设您有如下代码:

代码语言:javascript
复制
$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);

是否有办法将这些类似的指令组合成一个可以称为:

代码语言:javascript
复制
change_stats("infrastructure");
change_stats("education");
change_stats("healthcare");

基本上,中的变量可以在其他变量名和函数名中使用吗?

提前谢谢。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-10-24 13:25:53

您可以使用PHP所称的“可变变量”来完成此操作。我希望您的示例是人为的,因为它看起来有点奇怪,但是假设变量和对象是全局的,您可以这样编写name_pet()函数:

代码语言:javascript
复制
function name_pet($type, $name)
{
    $class='the_'.$type;
    $var=$type.'_name';

    $GLOBALS[$class]->setName($name);
    $GLOBALS[$var]=$name;
}

编辑:这个答案指的是问题的早期版本。

票数 3
EN

Stack Overflow用户

发布于 2009-10-24 13:15:28

我不确定这个函数,但是您可以使用__set做类似的事情

代码语言:javascript
复制
$data;
function __set($key, $val) {
 $this->data["$key"] = $val;
}

是的,您可以动态使用变量。

代码语言:javascript
复制
$foo = "bar";
$dynamic = "foo";

echo $$dynamic; //would output bar
echo $dynamic; //would output foo
票数 0
EN

Stack Overflow用户

发布于 2009-10-24 13:16:21

是的,这是可能的,看看这里的讨论和这里的教程。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1617976

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档