json - Compare two StdClass objects with PHP

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 usedvar_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
fromJSON
to StdClass, like the second one:
$object1 = (object)[
"null" => null,
"int" => 1,
];
But still...false
.
Answer
Solution:
There are two methods for comparing objects. Using the===
operator returnstrue
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
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: ftp_put(): can't open that file: no such file or directory
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.