Reputation: 2471
I'm learning about spl_object_hash()
and don't quite understand what's behind the scene in this case:
$obj = new stdClass;
$id1 = spl_object_hash($obj);
$id2 = spl_object_hash(new stdClass);
echo $id1.'<br>'.$id2;
Q1. Why $id1 !== $id2
?
In the reference:
When an object is destroyed, its hash may be reused for other objects.
Q.2 Is there something relates to that statement? Or I missed something else?
Upvotes: 2
Views: 1629
Reputation: 526
Let's examine your code step by step.
(1) $obj = new stdClass;
(2) $id1 = spl_object_hash($obj);
(3) $id2 = spl_object_hash(new stdClass);
(4) echo $id1.'<br>'.$id2;
1: Create a new stdClass object.
2: Get a hash for this object.
3: Get a hash for another (entirely different) stdClass object.
4: Echo the ids.
I believe the confusion comes from the third step. You make a new object, completely different from the first one, although it's the same type (class). And the spl_object_hash operates on the "object level", meaning it will return a different hash for different objects.
Upvotes: 2
Reputation: 522210
What does spl_object_hash
do?
[Returns a] string that is unique for each currently existing object and is always the same for each object.
To clarify that statement: if you have object A, each time you hash object A, it'll return the same hash value. If you have object A and object B, even if both are of the same type and contain the same values, their hashes will differ, because they're not the same object (instance).
Since you have two different objects, it's expected that their respective ids differ.
Upvotes: 8