2009-10-24 76 views
1

在PHP中,变量名说,你有一些像这样的代码:变量函数和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"); 

基本上,你能在其他变量名和函数名称中使用变量在PHP?

在此先感谢。

+0

你能告诉你如何定义$ the_cat吗? – 2009-10-24 13:20:13

+0

更改了示例,使其更清晰一些。 – 2009-10-24 13:29:23

+0

增加了一些额外的代码,使其更清晰。基本上,我有一系列的变量在类中被全部改变。 – 2009-10-24 13:37:05

回答

3

你可以使用PHP调用"variable variables"来做到这一点。我希望你的例子是人为的,因为它看起来有点古怪,但假设变量和对象是全球性的,你可以写这样的name_pet()函数:

function name_pet($type, $name) 
{ 
    $class='the_'.$type; 
    $var=$type.'_name'; 

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

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

+0

+1用于直接回答问题。 变量变量的难点在于它们使代码难以阅读和维护。当我编写代码时,我会避免它们,当我在代码中找到它们时,我会将它们重构。 – 2009-10-24 13:33:16

0

我不知道有关的功能,但你可以使用__set

$data; 
function __set($key, $val) { 
$this->data["$key"] = $val; 
} 

做类似的东西,是的,你可以使用变量动态

$foo = "bar"; 
$dynamic = "foo"; 

echo $$dynamic; //would output bar 
echo $dynamic; //would output foo 
0

要回答你的问题:是的,你可以使用变量作为变量名,使用$ {$ varname}语法。

但是,这似乎并不适合您在此尝试执行的操作,因为设置$ {_ petname}变量需要它们在name_pet函数的作用域中。

你能详细说明一下你试图做什么吗?

一些建议:有宠物类(或任何它是猫,狗和鱼)返回正在设置的名称,所以你可以做$ fish_name = $ the_fish-> setName(“Goldie”) ;因为该信息现在存储在对象中,所以您可以简单地调用$ the_fish-> getName();否则,将不会使用$ fish_name。你会在哪里使用$ the_fish。

希望这会帮助吗?

0

这是一个有趣的问题,因为这是一种常见模式,在重构时特别注意。

在纯功能性的方式,你可以使用一些这样的代码:

function rand_or_min($value, $key, $country) { 
    $rand = mt_rand(0,100); 
    if ($rand < $value) { $rand = $value; } 
    // do something 
    call_user_func(array($country, 'set_' . $value), array($rand)); 
} 

$arr = array('infrastructure' => 5,'education' => 3,'healthcare' => 80); 
array_walk($arr, 'rand_or_min', $country); 

虽然上述作品很好,我会强烈建议您使用更多的面向对象路径。每当你看到像上面这样的模式时,你应该考虑上课和下课。为什么?因为有重复的行为和类似的状态(变量)。

在一个更面向对象的方式,实现这一点的,像这样:

class SomeBasicBehavior { 

    function __construct($min = 0) { 
     $rand = mt_rand(0,100); 
     if($rand < $min) { $rand = $min }; 
     return $rand; 
    } 

} 

class Infrastructure extends SomeBasicBehavior { 
} 

class Education extends SomeBasicBehavior { 
} 

class Healthcare extends SomeBasicBehavior { 
} 

$country->set_infrastructure(new Infrastructure()); 
$country->set_education(new Education() }; 
$country->set_healthcare(new Healthcare() }; 

它不仅是更具可读性,但它也更可扩展性和可测试性。您的“做某事”可以轻松实现为每个类中的成员函数,并且它们的行为可以根据需要共享(使用SomeBasicBehavior类)或按需要进行封装。