2012-10-20 111 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