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 ) ]

但是,我想通过引用传递,因为找到的数组需要在之后进行修改。以前有人遇到过这个问题,可以建议他如何解决吗?

4

1 回答 1

1

您在每次调用的功能块开头分配NULL给。$lastShop因此它总是重置为NULL

我在文档中找到了它:

引用不是静态存储的:[…]

此示例演示了在为静态变量分配引用时,&get_instance_ref()第二次调用该函数时不会记住它。

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

于 2012-10-20T17:40:01.713 回答