Spl_object_hash, objects are not identical

I have two object variables in PHP, call them $a and $b . I assume that they are both the same object. Indeed, the call to spl_object_hash() confirms this, but each of them has different properties.

When I run:

 if(spl_object_hash($a) === spl_object_hash($b)){ echo "SAME HASH\n"; }else{ echo "DIFFERENT HASH\n"; } if(print_r($a,TRUE) === print_r($b,TRUE)){ echo "SAME PRINT_R\n"; }else{ echo "DIFFERENT PRINT_R\n"; } if($a === $b){ echo "IDENTICAL"; }else{ echo "NOT IDENTICAL"; } 

I get:

 SAME HASH DIFFERENT PRINT_R NOT IDENTICAL 

It puzzled me. When on one object are there really two different objects?

+7
source share
2 answers

There is a difference between being the same object and having the same properties.

 $a = new stdClass("same", "parameters", 1337); $b = new stdClass("same", "parameters", 1337); var_dump($a == $b); //True var_dump($a === $b); //False! $b = $a; var_dump($a === $b); //Now true. 
+6
source

Depending on the version of PHP and the operating system, PHP can distinguish two hash strings from integers before comparing them (because they look like numbers). Either because the resulting numbers are very large, or contain letters, casting can lead to data loss and, thus, lead to the same int value for both lines. Try the following:

 if ('X'.spl_object_hash($a) === 'X'.spl_object_hash($b)) { ... 
+2
source

All Articles