interface Hashable (View source)

Hashable is an interface which allows objects to be used as keys. It’s an alternative to spl_object_hash(), which determines an object’s hash based on its handle: this means that two objects that are considered equal by an implicit definition would not treated as equal because they are not the same instance.

hash() is used to return a scalar value to be used as the object's hash value, which determines where it goes in the hash table. While this value does not have to be unique, objects which are equal must have the same hash value.

equals() is used to determine if two objects are equal. It's guaranteed that the comparing object will be an instance of the same class as the subject.

Methods

bool
equals(object $obj)

Determines whether another object is equal to the current instance.

mixed
hash()

Returns a scalar value to be used as the hash value of the objects.

Details

bool equals(object $obj)

Determines whether another object is equal to the current instance.

This method allows objects to be used as keys in structures such as Ds\Map and Ds\Set, or any other lookup structure that honors this interface.

Note: It's guaranteed that $obj is an instance of the same class.

Caution: It's important that objects which are equal also have the same hash value.

Parameters

object $obj

The object to compare the current instance to, which is always an instance of the same class.

Return Value

bool

True if equal, false otherwise.

See also

https://www.php.net/manual/en/ds-hashable.hash.php

mixed hash()

Returns a scalar value to be used as the hash value of the objects.

While the hash value does not define equality, all objects that are equal according to Ds\Hashable::equals() must have the same hash value. Hash values of equal objects don't have to be unique, for example you could just return TRUE for all objects and nothing would break - the only implication would be that hash tables then turn into linked lists because all your objects will be hashed to the same bucket. It's therefore very important that you pick a good hash value, such as an ID or email address.

This method allows objects to be used as keys in structures such as Ds\Map and Ds\Set, or any other lookup structure that honors this interface.

Caution: Do not pick a value that might change within the object, such as a public property. Hash table lookups would fail because the hash has changed.

Caution: All objects that are equal must have the same hash value.

Return Value

mixed

A scalar value to be used as this object's hash value.