首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

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

发布于 2025-05-15 09:24:46
0
40

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"。

评论
一个月内的热帖推荐
啊龙
Lv.1普通用户

9545

帖子

31

小组

3242

积分

赞助商广告
站长交流