PHP Conference Japan 2024

SplObjectStorage::offsetSet

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

SplObjectStorage::offsetSet將資料與儲存區中的物件建立關聯

說明

public SplObjectStorage::offsetSet(物件 $object, 混合 $info = null): void

將資料與儲存區中的物件建立關聯。

注意事項:

SplObjectStorage::offsetSet()SplObjectStorage::attach() 的別名。

參數

object

要與資料關聯的 物件

info

要與 物件 關聯的資料。

傳回值

無傳回值。

範例

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

<?php
$s
= new SplObjectStorage;

$o1 = new stdClass;

$s->offsetSet($o1, "hello"); // 類似於 $s[$o1] = "hello";

var_dump($s[$o1]);
?>

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

string(5) "hello"

參見

新增註釋

使用者貢獻的註釋 1 則註釋

aderh
1 年前
雖然 `offsetSet` 應該是 `attach` 的別名,但實際結果並非如此。當繼承 SplObjectStorage 類別時,預期修改 `attach` 也會影響 `offsetSet`。 然而,似乎它們都需要被繼承覆寫。請參考以下結果...

<?php

declare(strict_types=1);

class
CustomSplObjectStorage extends SplObjectStorage
{
public function
offsetSet(mixed $object, mixed $info = null): void
{
print(
"offsetSet called\n");
parent::offsetSet($object, $info);
}

public function
attach(mixed $object, mixed $info = null): void
{
print(
"attach called\n");
parent::attach($object, $info);
}
}

$a = new CustomSplObjectStorage();
$a[new stdClass()] = 'ok';
$a->attach(new stdClass(), 'ok');
?>

這會印出
```
offsetSet called
attach called
```

然而我們預期會是…

```
offsetSet called
attach called
attach called
```

…如果 `offsetSet` 真的是 `attach` 的別名。我不確定這是否是故意的。
To Top