我正在尝试编写一个“智能”数组搜索函数,它会记住最后找到的项目。
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 ) ]
但是,我想通过引用传递,因为找到的数组需要在之后进行修改。以前有人遇到过这个问题,可以建议他如何解决吗?