Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spl_object_hash matches, objects not identical

Tags:

oop

php

I have two object variables in PHP, let's call them $a and $b. I assume they're both the same object. And, indeed, a call to spl_object_hash() confirms this, but they each have 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

This has got me baffled. When is the same object actually two different objects?

like image 354
Ross McFarlane Avatar asked Nov 08 '11 16:11

Ross McFarlane


1 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.
like image 192
Madara's Ghost Avatar answered Oct 16 '22 07:10

Madara's Ghost