查詢

SplObjectStorage::offsetSet()函式—用法及示例

「 將一個物件與一個資料關聯起來,並將其新增到SplObjectStorage物件中 」


SplObjectStorage::offsetSet()函式用於將一個物件與一個資料關聯起來,並將其新增到SplObjectStorage物件中。該函式的用法如下:

void SplObjectStorage::offsetSet ( object $object , mixed $data )

引數說明:

  • $object:要與資料關聯的物件。
  • $data:要關聯的資料。

示例:

// 建立一個SplObjectStorage物件
$storage = new SplObjectStorage();

// 建立兩個物件
$obj1 = new stdClass();
$obj2 = new stdClass();

// 將物件與資料關聯並新增到SplObjectStorage物件中
$storage->offsetSet($obj1, 'Data for object 1');
$storage->offsetSet($obj2, 'Data for object 2');

// 遍歷SplObjectStorage物件並輸出關聯的資料
foreach ($storage as $object) {
    echo "Object: ";
    var_dump($object);
    
    echo "Data: ";
    var_dump($storage->offsetGet($object));
    echo "\n";
}

輸出結果:

Object: object(stdClass)#1 (0) {
}
Data: string(16) "Data for object 1"

Object: object(stdClass)#2 (0) {
}
Data: string(16) "Data for object 2"

在上面的示例中,我們首先建立了一個SplObjectStorage物件。然後,我們建立了兩個stdClass物件$obj1和$obj2。使用offsetSet()函式,我們將這兩個物件與相應的資料關聯並新增到SplObjectStorage物件中。最後,我們使用foreach迴圈遍歷SplObjectStorage物件,並使用offsetGet()函式獲取關聯的資料並輸出。

補充糾錯
熱門PHP函式
分享連結