I have two objects, which are the same, but written in different methods. One is JSON (decoded):
$object1 = json_decode('{"null":null,"int":1}');
And one is StdClass:
$object2 = (object)[
"null" => null,
"int" => 1,
];
As you can see, they contain the exact same structure (both keys and values). nothing is different. So it should be equal. but... it's not.
echo json_encode($object1 === $object2);
// -> false
I thought maybe i'm wrong, and JSON is not an StdClass. so I used var_dump
and still, they are the same:
object(stdClass)#1 (2) {
["null"]=>
NULL
["int"]=>
int(1)
}
object(stdClass)#2 (2) {
["null"]=>
NULL
["int"]=>
int(1)
}
Now I'm frustrated and I don't know how to compare two objects, and detect changes between them.
Is it possible?
Edit:
I thought it might work if I'll change $object1
from JSON
to StdClass, like the second one:
$object1 = (object)[
"null" => null,
"int" => 1,
];
But still... false
.
There are two methods for comparing objects. Using the ===
operator returns true
if the objects you are comparing are the same instance of the same class. i.e. They are the same object.
Using the ==
operator returns true if all the properties of both objects are equal, and the objects are instances of the same class.
You're comparing two different objects, so ===
will returns false, but ==
should return true.
Reference: https://www.php.net/manual/en/language.oop5.object-comparison.php