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

后端 未结 4 541
攒了一身酷
攒了一身酷 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:52

    The only way to access the all (public, protected and private) properties of an object without modifying it is through reflection. You could, if you wanted to, clone the object before it's modified and then compare them by using the reflection functions to loop through the different properties of one of the two objects and comparing values. That would effectively tell you what properties have changed.

    If all you care to see is whether or not the objects have changed, you can use the == or === operators. Have a look at the comparing objects section of PHP's documentation.

    That said, wouldn't just be easier to keep track of what you've changed as you change them?

提交回复
热议问题