English | 简体中文 | 繁體中文
查询

WeakMap::offsetExists()函数—用法及示例

「 检查指定的键是否存在于WeakMap对象中 」


PHP的WeakMap::offsetExists()方法用于检查指定的键是否存在于WeakMap对象中。

用法:

public WeakMap::offsetExists( mixed $key ) : bool

参数:

  • $key:要检查的键。

返回值:

  • 如果键存在于WeakMap对象中,则返回true;否则返回false。

示例:

// 创建WeakMap对象
$map = new WeakMap();

// 创建对象作为键
$obj1 = new stdClass();
$obj2 = new stdClass();

// 将对象作为键添加到WeakMap中
$map[$obj1] = 'Value 1';

// 检查键是否存在于WeakMap中
if ($map->offsetExists($obj1)) {
    echo 'Key exists';
} else {
    echo 'Key does not exist';
}

// 检查不存在的键
if ($map->offsetExists($obj2)) {
    echo 'Key exists';
} else {
    echo 'Key does not exist';
}

输出:

Key exists
Key does not exist

在示例中,我们首先创建了一个WeakMap对象,并使用两个不同的对象作为键添加到WeakMap中。然后,我们使用offsetExists()方法检查第一个对象是否存在于WeakMap中,由于存在,所以输出"Key exists"。然后,我们检查第二个对象是否存在于WeakMap中,由于不存在,所以输出"Key does not exist"。

补充纠错
上一个函数: WeakMap::offsetGet()函数
下一个函数: WeakMap::getIterator()函数
热门PHP函数
分享链接