LoginSignup
1
1

More than 5 years have passed since last update.

SplObjectStorageを使ってみる

Last updated at Posted at 2016-03-28
<?php

$o1 = new stdClass();
$o2 = new stdClass();
$o3 = new stdClass();

$storage = new SplObjectStorage();

// オブジェクトをキーに値を格納できる
$storage[$o1] = 'hoge';
$storage[$o2] = 'piyo';

echo $storage[$o1] . PHP_EOL;
echo $storage[$o2] . PHP_EOL;

$storage = new SplObjectStorage();

// attachでオブジェクトを追加
$storage->attach($o1);
$storage->attach($o2);
$storage->attach($o3);

// detachでオブジェクトを削除
$storage->detach($o3);

// countで格納されているオブジェクトの数を取得
echo $storage->count() . PHP_EOL;   # 2

// containsでオブジェクトの存在を確認
if ($storage->contains($o1))
    // オブジェクトの識別子を取得
    echo sprintf('Object 1: %s', $storage->getHash($o1)) . PHP_EOL;
if ($storage->contains($o2))
    echo sprintf('Object 2: %s', $storage->getHash($o2)) . PHP_EOL;
if ($storage->contains($o3))
    echo sprintf('Object 3: %s', $storage->getHash($o3)) . PHP_EOL;

try {
} catch (Exception $e) {
    echo get_class($e) . PHP_EOL;
}

// 参考) spl_object_hashで取得できる値: $o1
echo sprintf('Object 1: %s', spl_object_hash($o1)) . PHP_EOL;

// 参考) Arrayのキーにオブジェクトを指定
// $storage[$o1] = 'Hoge'; // もちろんできない

// serializeとunserializeを用いてのオブジェクト追加
echo 'before: ' . $storage->count() . PHP_EOL; # before: 2

$storageAdd = new SplObjectStorage();
$storageAdd->attach(new stdClass());
$storageAdd->attach(new stdClass());

$str = $storageAdd->serialize();

$storage->unserialize($str);

echo 'after: ' . $storage->count() . PHP_EOL; # after: 4
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1