PHP Conference Japan 2024

SplObjectStorage::offsetGet

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplObjectStorage::offsetGet傳回與物件關聯的資料

說明

public SplObjectStorage::offsetGet(物件 $object): mixed

傳回儲存空間中與物件關聯的資料。

參數

object

要尋找的物件

傳回值

先前在儲存空間中與物件關聯的資料。

錯誤/例外

當找不到 object 時,會擲出 UnexpectedValueException

範例

範例 #1 SplObjectStorage::offsetGet() 範例

<?php
$s
= new SplObjectStorage;

$o1 = new stdClass;
$o2 = new stdClass;

$s[$o1] = "hello";
$s->attach($o2);


var_dump($s->offsetGet($o1)); // 類似於 $s[$o1]
var_dump($s->offsetGet($o2)); // 類似於 $s[$o2]
?>

上述範例將輸出類似以下的內容

string(5) "hello"
NULL

另請參閱

新增註記

使用者貢獻的註記 2 則註記

acgrid
8 年前
PHP7.0.7 中 SplObjectStorage 的效能提升了很多。

SplObjectStorage
double(1.3110690116882)
[物件雜湊 => 值]
double(2.4147419929504)
kontrollfreak+php at gmail dot com
9 年前
SplObjectStorage::offsetGet() 的速度可能會變得非常慢,取決於相關聯的資料 (PHP 5.6)。

<?php

// SplObjectStorage
$object = new stdClass;
$test = new SplObjectStorage;
$test->attach($object, str_repeat("\0", 1024*1024));
$start = microtime(true);
for (
$i = 0; $i < 1000000; $i++) {
$test->offsetGet($object);
}
var_dump(microtime(true) - $start); // 76 秒!

// 陣列 + spl_object_hash()
$object = new stdClass;
$test = [];
$test[spl_object_hash($object)] = str_repeat("\0", 1024*1024);
$start = microtime(true);
for (
$i = 0; $i < 1000000; $i++) {
$temp = $test[spl_object_hash($object)];
}
var_dump(microtime(true) - $start); // 0.3 秒
To Top