Is there a __equals method in PHP like there is in Java?

前端 未结 5 1029
执念已碎
执念已碎 2021-01-01 09:40

Is there a pattern or magic method you can use in PHP to define when to compare two instances of a class?

For example, in Java I could easily override the equa

5条回答
  •  长发绾君心
    2021-01-01 10:06

    If you want to compare your custom object, you can do it like this:

    $time1 = new MyTimeClass("09:35:12");
    $time2 = new MyTimeClass("09:36:09");
    
    if($time1 > $time2) echo "Time1 is bigger";
    else echo "Time2 is bigger";
    
    //result: Time2 is bigger
    

    It compares the first property found in the class, in my case an int value that holds the total number of seconds in the given time. If you put the $seconds property on top you'll notice that it gives an unexpected 'Time1 is bigger'.

    class MyTimeClass {
        public $intValue;
        public $hours;
        public $minutes;
        public $seconds;
    
        public function __construct($str){
            $array = explode(":",$str);
            $this->hours = $array[0];
            $this->minutes = $array[1];
            $this->seconds = $array[2];
            $this->intValue = ($this->hours * 3600) + ($this->minutes * 60) + $this->seconds;
        }
    }
    

提交回复
热议问题