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

SplObjectStorage::offsetGet()函数—用法及示例

「 获取存储在SplObjectStorage对象中的指定对象的关联数据 」


SplObjectStorage::offsetGet()函数用于获取存储在SplObjectStorage对象中的指定对象的关联数据。

用法:

public mixed SplObjectStorage::offsetGet ( object $object )

参数:

  • $object:要获取关联数据的对象。

返回值:

  • 返回与指定对象关联的数据。如果对象不存在于SplObjectStorage中,则返回NULL。

示例:

// 创建一个SplObjectStorage对象
$storage = new SplObjectStorage();

// 创建两个对象
$obj1 = new stdClass();
$obj2 = new stdClass();

// 将对象与数据关联并存储到SplObjectStorage中
$storage->attach($obj1, 'Data for obj1');
$storage[$obj2] = 'Data for obj2';

// 获取关联数据
echo $storage->offsetGet($obj1);  // 输出:Data for obj1
echo $storage[$obj2];  // 输出:Data for obj2

// 尝试获取不存在的对象的关联数据
echo $storage->offsetGet(new stdClass());  // 输出:NULL

在上面的示例中,我们首先创建了一个SplObjectStorage对象,并创建了两个stdClass对象$obj1和$obj2。然后,我们使用attach()方法和数组索引语法将这两个对象与关联数据一起存储在SplObjectStorage中。

最后,使用offsetGet()方法获取$obj1对象的关联数据,并使用数组索引语法获取$obj2对象的关联数据。如果我们尝试获取一个不存在于SplObjectStorage中的对象的关联数据,将返回NULL。

补充纠错
热门PHP函数
分享链接