2012-10-20 156 views
0

我想寫一個「智能」數組搜索功能,將記住最後找到的項目。分配參考靜態變量

function &GetShop(&$shops, $id) { 
    static $lastShop = null; 
    if ($lastShop == null) { 
     echo "lastShop is null <br/>"; 
    } else { 
     echo "lastShop: [" . print_r($lastShop, true) . "]<br/>"; 
    } 
    if ($lastShop != null && $lastShop['id'] == $id) { 
     return $lastShop; 
    } 
    for ($i = 0; $i < count($shops); $i++) { 
     if ($shops[$i]['id'] == $id) { 
      $lastShop = &$shops[$i]; 
      return $shops[$i]; 
     } 
    } 
} 

$shops = array(
    array("id"=>"1", "name"=>"bakery"), 
    array("id"=>"2", "name"=>"flowers") 
); 

GetShop($shops, 1); 
GetShop($shops, 1); 
GetShop($shops, 2); 
GetShop($shops, 2); 

然而,似乎是與行的發行人:

$lastShop = &$shops[$i]; 

當我運行這個功能,因爲它是,我得到這樣的輸出:

lastShop is null 
lastShop is null 
lastShop is null 
lastShop is null 

當我刪除「&」,而不是價值傳遞,它工作正常:

lastShop is null 
lastShop: [Array ([id] => 1 [name] => bakery) ] 
lastShop: [Array ([id] => 1 [name] => bakery) ] 
lastShop: [Array ([id] => 2 [name] => flowers) ] 

但是我想通過引用傳遞,因爲找到的數組需要隨後修改。有人遇到過這個問題,並可以建議他如何解決它?

回答

1

在每個調用的功能塊開始處,您正在爲 $lastShop分配 NULL。因此它總是重置爲 NULL

我發現它在文檔中:

引用並不是靜態地存儲:[...]

這個例子表明,分配到一個靜態變量的引用時,它不是當你調用記憶&get_instance_ref()功能第二次。

http://php.net/manual/en/language.variables.scope.php#language.variables.scope.references

+0

似乎這不是解決問題(已經嘗試過),因爲按照[PHP文檔(http://www.php.net/manual/en/language.variables。 scope.php#language.variables.scope.static)函數中的靜態變量只在第一次調用時被初始化。 – quentinadam

+0

@goldmine查看更新 – feeela

+0

謝謝。你會對我如何實現我想要做的事情有任何建議嗎(即將引用存儲到數組中的最後一個找到的項)? – quentinadam