마지막으로 발견 된 항목을 기억할 수있는 "스마트"배열 검색 기능을 작성하려고합니다. 내가 제거정적 변수에 대한 참조 지정
lastShop is null
lastShop is null
lastShop is null
lastShop is null
: 그대로 내가이 기능을 실행하면
$lastShop = &$shops[$i];
, 나는이 출력을 얻을 :
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 is null
lastShop: [Array ([id] => 1 [name] => bakery) ]
lastShop: [Array ([id] => 1 [name] => bakery) ]
lastShop: [Array ([id] => 2 [name] => flowers) ]
그러나 발견 된 배열을 나중에 수정해야하기 때문에 참조로 전달하고 싶습니다. 누군가이 문제를 전에 만났고 어떻게 해결했는지 조언 할 수 있었습니까?
은 (http://www.php.net/manual/en/language.variables에서 [PHP 문서]에 따라, (그것을 시도했다). scope.php # language.variables.scope.static) 함수의 정적 변수는 첫 번째 호출에서만 초기화됩니다. – quentinadam
@ goldmine 업데이트 참조 – feeela
고마워요. 내가하려는 일을 어떻게 달성 할 수 있는지 (즉, 배열에서 마지막으로 발견 된 항목에 대한 참조를 저장하는) 조언을 해 주시겠습니까? – quentinadam