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

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

    Simple example comparing dto class through reflection

    class InvoiceDetails
    {
        /** @var string */
        public $type;
    
        /** @var string */
        public $contractor;
    
        /** @var string */
        public $invoiceNumber;
    
        /** @var \DateTimeInterface|null */
        public $saleDate;
    
        /** @var \DateTimeInterface|null */
        public $issueDate;
    
        /** @var \DateTimeInterface|null */
        public $dueDate;
    
        /** @var string */
        public $payment;
    
        /** @var string */
        public $status;
    
    
        public function isEqual(InvoiceDetails $details): bool
        {
            $reflection = new \ReflectionClass(self::class);
    
            /** @var \ReflectionProperty $property */
            foreach ($reflection->getProperties() as $property) {
                $name = $property->getName();
                if ($this->$name !== $details->$name) {
                    return false;
                }
            }
    
            return true;
        }
    
    }
    

提交回复
热议问题