CakeFest 2024: The Official CakePHP Conference

SplObjectStorage::getHash

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

SplObjectStorage::getHash 中に含むオブジェクトの一意な識別子を算出する

説明

public SplObjectStorage::getHash(object $object): string

このメソッドは、SplObjectStorage オブジェクトに追加されたオブジェクトの識別子を算出します。

SplObjectStorage の実装では、 spl_object_hash() と同じ値を返します。

ストレージオブジェクトには、同じ識別子のオブジェクトを複数格納することはできません。 それを利用して、セット (一意な値のコレクション) を実装するのにも使えます。 オブジェクトが一意であるという性質は、この関数の返す値が一意であるということで実現できます。

パラメータ

object

識別子を算出したいオブジェクト。

戻り値

算出した識別子を文字列で返します。

エラー / 例外

返された値が文字列でない場合に RuntimeException をスローします。

例1 SplObjectStorage::getHash() の例

<?php
class OneSpecimenPerClassStorage extends SplObjectStorage {
public function
getHash($o) {
return
get_class($o);
}
}
class
A {}

$s = new OneSpecimenPerClassStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o3 = new A;

$s[$o1] = 1;
// $o2 は $o1 に等しいとみなされ、値が置き換えられます
$s[$o2] = 2;
$s[$o3] = 3;

// これらは先ほどのオブジェクトと等しいとみなされ、
// さきほど格納した値にアクセスできるようになります
$p1 = new stdClass;
$p2 = new A;
echo
$s[$p1], "\n";
echo
$s[$p2], "\n";
?>

上の例の出力は、 たとえば以下のようになります。

2
3

参考

add a note

User Contributed Notes 1 note

up
7
aron dot duby at gmail dot com
11 years ago
This also appears to be the function which gets used within the contains() function, so if all the objects you are storing already have a unique id you can overwrite this function with your own class.

<?php
class UserStorage extends SPLObjectStorage{
public function
getHash($obj){
return
$obj->id;
}
}

$us = new UserStorage();
$user1 = new User(1);
$user2 = new User(2);

$us->attach($user1);
$us->attach($user2);

$me = new User(2);

// the following would normally fail since they are two separate objects
// but it works now with our extended getHash()
$us->contains($me);

?>
To Top