2009-10-24 75 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類)或按需要進行封裝。