quentinadam
quentinadam

Reputation: 3150

Assign reference to static variable

I am trying to write a "smart" array search function that would remember the last found item.

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

However, there seems to be an issuer with the line:

$lastShop = &$shops[$i];

When I run this function as it is, I get this output:

lastShop is null 
lastShop is null 
lastShop is null 
lastShop is null 

When I remove the "&" to pass by value instead, it works fine:

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

I would however like to pass by reference because the found array needs to be modified afterwards. Has somebody encountered this issue before and could advice how he solved it?

Upvotes: 0

Views: 178

Answers (1)

feeela
feeela

Reputation: 29942

You are assigning NULL to $lastShop at the beginning of the function block on each call. Thus it is always reset to NULL.

I found it in the documentation:

References are not stored statically: […]

This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.

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

Upvotes: 1

Related Questions