[英]Assign reference to static variable
我正在尝试编写一个“智能”数组搜索功能,该功能将记住最后找到的项目。
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 ) ]
但是,我想按引用传递,因为之后需要修改找到的数组。 以前有人遇到过这个问题,可以建议他如何解决吗?
您将在每次调用的功能块开头将
NULL
分配给
$lastShop
。
因此,它总是重置为
NULL
。
我在文档中找到了它:
引用不是静态存储的:[…]
此示例说明,当给静态变量分配引用时,第二次调用
&get_instance_ref()
函数时,它不会被记住。
http://php.net/manual/zh-CN/language.variables.scope.php#language.variables.scope.references
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.