<?php
class HashableObject implements \Ds\Hashable
{
/**
* An arbitrary value to use as the hash value. Does not define equality.
*/
private $value;
public function __construct($value)
{
$this->value = $value;
}
public function hash()
{
return $this->value;
}
public function equals($obj): bool
{
return $this->value === $obj->value;
}
}
$map = new \Ds\Map();
$obj = new \ArrayIterator([]);
// Using the same instance multiple times will overwrite the previous value.
$map->put($obj, 1);
$map->put($obj, 2);
// Using multiple instances of the same object will create new associations.
$map->put(new \stdClass(), 3);
$map->put(new \stdClass(), 4);
// Using multiple instances of equal hashable objects will overwrite previous values.
$map->put(new \HashableObject(1), 5);
$map->put(new \HashableObject(1), 6);
$map->put(new \HashableObject(2), 7);
$map->put(new \HashableObject(2), 8);
var_dump($map);
?>
The above example will output
something similar to:
object(Ds\Map)#1 (5) {
[0]=>
object(Ds\Pair)#7 (2) {
["key"]=>
object(ArrayIterator)#2 (1) {
["storage":"ArrayIterator":private]=>
array(0) {
}
}
["value"]=>
int(2)
}
[1]=>
object(Ds\Pair)#8 (2) {
["key"]=>
object(stdClass)#3 (0) {
}
["value"]=>
int(3)
}
[2]=>
object(Ds\Pair)#9 (2) {
["key"]=>
object(stdClass)#4 (0) {
}
["value"]=>
int(4)
}
[3]=>
object(Ds\Pair)#10 (2) {
["key"]=>
object(HashableObject)#5 (1) {
["value":"HashableObject":private]=>
int(1)
}
["value"]=>
int(6)
}
[4]=>
object(Ds\Pair)#11 (2) {
["key"]=>
object(HashableObject)#6 (1) {
["value":"HashableObject":private]=>
int(2)
}
["value"]=>
int(8)
}
}