2017-05-31 91 views
1

跨越下面的PHP代碼片段需要給出關於PHP代碼片段一些澄清

class SearchGoogle extends Thread 
{ 
    public function __construct($query) 
    { 
     $this->query = $query; 
    } 

    public function run() 
    { 
     $this->html = file_get_contents('http://google.fr?q='.$this->query); 
    } 
} 

$searches = ['cats', 'dogs', 'birds']; 
foreach ($searches as &$search) { 
    $search = new SearchGoogle($search); 
    $search->start(); 
} 

來到我的理解如下foreach循環有問題。對我來說,看起來像 的$search變量同時既用作$searches陣列的元素和作爲SearchGoogle一個實例。這在PHP中可能嗎?

+1

由於它是用作參考('如&$ search',請注意符號),這意味着在$搜索原始條目(字符串''cats''例如)獲取與SearchGoogle'的'實例覆蓋與該搜索詞有關。在循環後,'$ searches'看起來像** **'SearchGoogle( '貓'),SearchGoogle( '狗'),SearchGoogle( '鳥')',而不是' '貓', '狗',「鳥「'。 – ccKep

+0

感謝您提供簡單而緊湊的解釋。那很酷。我如何將你的帖子標記爲幫助我的帖子? –

+0

這是一條評論,你不能(除了upvoting)。我應該張貼作爲一個答案,但不喜歡它滿足了我的標準;-)你可以只接受@ÁlvaroGonzález的答案,因爲它具有相同的信息。 – ccKep

回答

0

PHP是弱類型,沒有什麼可以阻止你重用一個變量:

$foo = 'Bar'; 
var_dump($foo); 
$foo = M_PI; 
var_dump($foo); 
$foo = new DateTime(); 
var_dump($foo); 
string(3) "Bar" 
float(3.1415926535898) 
object(DateTime)#1 (3) { 
    ["date"]=> 
    string(26) "2017-05-31 12:29:01.000000" 
    ["timezone_type"]=> 
    int(3) 
    ["timezone"]=> 
    string(13) "Europe/Madrid" 
} 

在這種情況下,雖然,代碼是大致相同的:

$searches = ['cats', 'dogs', 'birds']; 
foreach ($searches as $index => $search) { 
    $searches[$index] = new SearchGoogle($search); 
    $searches[$index]->start(); 
} 

在其他字,它將用SearchGoogle類的實例替換數組中的字符串。