2013-05-17 27 views
1

變量我有PHP代碼:如何插入內部變量

$rand = rand(1,5); 

,我想定義具有像蘭德函數的名稱VAR:

$$rand // if $rand= 1 then the var will be $1 

,然後做

switch($rand){ 
case(1): 
$$rand = 'How many legs dog has ?'; 
$ans= '4';  } 

該代碼用於定義安全問題。 希望有人得到了我的想法。我該怎麼做 ?

+0

嘗試$ {$ rand} - 爲什麼你想要它? – hexblot

+0

'$$ rand'在PHP中是有效的語法;但是,'$ 1'不是合法的變量名稱。試試'$ rand =「r」.rand(1,5); $$ rand'。 – Passerby

+2

不要 - 用數組代替 – jantimon

回答

1
// Sanitize the arrays 
$questions = array(); 
$answers = array(); 

// Build some questions and assign to the questions array 
$questions[0] = 'How many legs does a dog have?'; 
$questions[1] = 'How many eyes does a human have?'; 
$questions[2] = 'How many legs does a spider have?'; 


// Add the answers, making sure the array index is the same as the questions array 
$answers[0] = 4; 
$answers[1] = 2; 
$answers[2] = 8; 


// Select a question to use 
$questionId = rand(0, count($questions)); 


// Output the question and answer 
echo 'questions: ' . $questions[$questionId]; 
echo 'answer: ' . $answers[$questionId]; 

PHP中的變量不能以數字開頭。

+0

Array!我怎麼沒有想到它!謝謝 ! –

0

$ {$ rand}是正確的方法。但請注意,您的變量名稱不能以數字開頭。

引述PHP manual

變量名遵循相同的規則,如PHP等標籤。有效的變量名稱以字母或下劃線開頭,後跟任意數量的字母,數字或下劃線。作爲正則表達式,它將如此表示:'[a-zA-Z_ \ x7f- \ xff] *'

+0

但是,'$ name = 1; $$ name ='var'; echo $ {1};'非常好。 – Leri

+0

@PLB技術上不是,因爲$$的名字仍然是1,這是無效的,它的方式是'$ name ='q1'; $$ name ='var'; echo $ name;' –

+0

@PhilCross http://codepad.viper-7.com/MGy28c :) – Leri

3

有時很方便能夠具有可變的變量名稱。即,可以動態設置和使用的變量名稱。一個正常的變量被設置與語句,例如:

<?php 
$a = 'hello'; 
?> 

變量變量取變量的值並設爲,作爲一個變量的名稱。在上面的例子中,你好,可以用兩個美元符號作爲變量的名字。即

<?php 
$$a = 'world'; 
?> 

此時兩個變量已經被定義並存儲在PHP符號樹:$ a的內容是「你好」和$ hello的內容是「世界」。因此,這樣的說法:

<?php 
echo "$a ${$a}"; 
?> 

產生完全相同的輸出:

<?php 
echo "$a $hello"; 
?> 

即它們都產生:世界你好。

爲了在數組中使用變量變量,必須解決模糊性問題。也就是說,如果你寫$$ a [1],那麼解析器需要知道你是否打算使用$ a [1]作爲變量,或者如果你想要$$ a作爲變量,然後是[1]索引那個變量。解決這種歧義的語法是:第一種情況爲$ {$ a [1]},第二種情況爲$ {$ a} [1]。

也可以使用變量屬性名稱來訪問類屬性。變量屬性名稱將在調用範圍內解析。例如,如果你有一個表達式,例如$ foo - > $ bar,那麼本地範圍將被檢查$ bar,並且它的值將被用作$ foo屬性的名稱。如果$ bar是一個數組訪問,這也是正確的。

+0

所以這[簡單的複製和粘貼](http://www.php.net/manual/en/language.variables.variable.php)?給你的來源提供參考(給予功勞)會很好。 – Passerby