2012-10-29 22 views
1

我有這樣的代碼定義的file_get_contents可變

<?php 
$a1 = 'http://www.hamooz.com'; 
$a2 = 'http://www.myegy.com'; 
$a3 = 'http://www.tech-wd.com/wd'; 
$num = rand(1,3); 

$numb = '$a'.$num; 

echo file_get_contents($numb); 
?> 

問題出現,如:

警告:的file_get_contents($ A3)function.file-GET-內容]:未能打開流:第9行的C:\ xampp \ htdocs \ ttt \ bessah.php中沒有這樣的文件或目錄

回答

3

變量變量是一種不好的做法。改用數組。

<?php 

$a = array(); 
$a[] = 'http://www.hamooz.com'; 
$a[] = 'http://www.myegy.com'; 
$a[] = 'http://www.tech-wd.com/wd'; 
$num = rand(0,2); 

$numb = $a[$num]; 

echo file_get_contents($numb); 
?> 

然而,對於這個特定的任務,也有一個shortcut

array_rand()

精選一個或多個隨機條目出的陣列的,並返回鍵(或多個密鑰)的隨機條目。

+1

@ AD7six如此。這是更多的教學目的,但array_rand肯定需要提及,我會添加它。 –

+0

感謝它的工作 –

+0

此外,該數組可以聲明爲'$ a = array('http://www.hamooz.com',...)' –

4

您需要做$numb = ${'a'.$num};,但使用數組解決方案作爲@ Pekka的答案。

0

我@Pekka同意你要複雜的代碼, 但如果你是絕對要使用動態變量,你可以這樣做:

<?php 
$a1="hello"; 
$b=1; 
echo ${"a$b"}; 
?> 
+0

這是一個很好的混淆方法。 –