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

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

    There is a whole site on php.net only dealing with comparing objects:

    http://php.net/manual/en/language.oop5.object-comparison.php

    Also a good read:

    http://www.tuxradar.com/practicalphp/6/12/0

    I would say you should use the "clone" method when copying your object and then later compare as said in the php.net article.

    Also a fast way would be by declaring a static method in the class that just compares the relevant "properties" like lets say "username", "password", "cookie",...

        class User
        {
    
        public $username;
        public $password;
        public $cookie;
    
        # other code
    
        public static function compare(&$obj1, &$obj2)
        {
        if ($obj1->username != $obj2->username)
            return 0
        if ($obj1->password != $obj2->password)
            return 0
        if ($obj1->cookie != $obj2->cookie)
            return 0
        return 1
        }
    
    
        };       
    

提交回复
热议问题