라이브러리
[PHP] WeakMap::offsetExists - 특정 객체가 맵에 있는지 확인합니다.
WeakMap::offsetExists
PHP 7.3 버전부터 WeakMap 클래스가 추가되었습니다. WeakMap은 키-값 쌍을 저장하는 WeakMap 객체를 제공하는 인터페이스입니다. WeakMap은 키가 객체일 때 유용합니다. 키가 객체일 때, WeakMap은 키가 더 이상 참조되지 않을 때 키를 자동으로 삭제합니다.
WeakMap::offsetExists 메소드는 키가 존재하는지 여부를 확인합니다. 이 메소드는 boolean 값을 반환합니다.
예제
#hostingforum.kr
php
class User {
public $name;
public $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
}
$user1 = new User('john', 'john@example.com');
$user2 = new User('jane', 'jane@example.com');
$weakMap = new WeakMap();
$weakMap[$user1] = 'john';
$weakMap[$user2] = 'jane';
var_dump($weakMap->offsetExists($user1)); // bool(true)
var_dump($weakMap->offsetExists($user2)); // bool(true)
unset($user1);
var_dump($weakMap->offsetExists($user1)); // bool(false)
// $user1이 더 이상 참조되지 않아 WeakMap에서 삭제되었다.
WeakMap::offsetExists 사용 예시
WeakMap::offsetExists 메소드는 키가 존재하는지 여부를 확인할 때 사용할 수 있습니다. 예를 들어, 객체를 캐싱할 때 사용할 수 있습니다.
#hostingforum.kr
php
class Cache {
private $cache;
public function __construct() {
$this->cache = new WeakMap();
}
public function get($key) {
if ($this->cache->offsetExists($key)) {
return $this->cache[$key];
} else {
return null;
}
}
public function set($key, $value) {
$this->cache[$key] = $value;
}
}
$cache = new Cache();
$user1 = new User('john', 'john@example.com');
$user2 = new User('jane', 'jane@example.com');
$cache->set($user1, 'john');
$cache->set($user2, 'jane');
var_dump($cache->get($user1)); // string(4) "john"
var_dump($cache->get($user2)); // string(4) "jane"
unset($user1);
var_dump($cache->get($user1)); // NULL
결론
WeakMap::offsetExists 메소드는 키가 존재하는지 여부를 확인할 때 사용할 수 있습니다. 이 메소드는 키가 객체일 때 유용합니다. 키가 객체일 때, WeakMap은 키가 더 이상 참조되지 않을 때 키를 자동으로 삭제합니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.