分配对静态变量的引用

时间:2012-10-20 17:35:26

标签: php

我正在尝试编写一个“智能”数组搜索功能,它会记住最后找到的项目。

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 

当我删除“&amp;”时相反,它传递值,它工作正常:

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

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

1 个答案:

答案 0 :(得分:1)

您在每次调用时在功能块的开头为NULL分配$lastShop。因此,它始终重置为NULL

我在文档中找到了它:

  

参考文献不会静态存储:[...]

     

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

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