简体   繁体   中英

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 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. ie 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.

See https://3v4l.org/UdFFT

Reference: https://www.php.net/manual/en/language.oop5.object-comparison.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM