What's the fastest way to compare two objects in PHP?

后端 未结 4 542
攒了一身酷
攒了一身酷 2021-02-13 17:00

Let\'s say I have an object - a User object in this case - and I\'d like to be able to track changes to with a separate class. The User object should not have to change it\'s be

4条回答
  •  礼貌的吻别
    2021-02-13 17:26

    Here is a piece of code that supports private properties:

    $reflection_1 = new \ReflectionClass($object_1);
    $reflection_2 = new \ReflectionClass($object_2);
    
    $props_1 = $reflection_1->getProperties();
    
    foreach ($props_1 as $prop_1) {
    
        $prop_1->setAccessible(true);
        $value_1 = $prop_1->getValue($object_1);
    
        $prop_2 = $reflection_2->getProperty($prop_1->getName());
    
        $prop_2->setAccessible(true);
        $value_2 = $prop_2->getValue($object_2);
    
        if ($value_1 === $value_2) {
            // ...
        } else {
            // ...
        }
    }
    


    Note that if $object_1 has properties that $object_2 doesn't have, the above code will produce errors when trying to access them.

    For such a case, you would need first to intersect $reflection_1->getProperties() with $reflection_2->getProperties().

提交回复
热议问题