Compare two StdClass objects with PHP

  comparison, json, php, stdclass

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.

Source: Ask PHP

LEAVE A COMMENT