Automatically check equality of two objects?

I need to check if two PHP objects are equal in terms of equal values. Of course, I could easily add a method isEqualTo(...)to a class that compares all the relevant values. However, the specific class will change in the near future, and I would like to know if there is any automated way to do this.

Example:

class Contact {
    private name;       // String
    private phone;      // Int
    private someObject; // Custom Object

    public function getName() {
        return $this->name;
    }

    public function setName($newName) {
        $this->name = $newName;
    }


    public function getPhone() {
        return $this->phone;
    }

    public function setPhone($newPhone) {
        $this->phone = $newPhone;
    }


    public function getSomeObject() {
        return $this->someObject;
    }

    public function setSomeObject($newObj) {
        $this->someObject = $newObj;
    }


    // Manual Solution 
    public function isEqualTo($contact) {
         result  = $this->name == $contact->getName();
         result &= $this->phone == $contact->getPhone();

         result &= $this->someObject == $contact->getSomeObject();

         return result;
    }
} 

This will obviously work. Of course, I know about the restriction of comparison someObject(you need a specific object to be true), but this is normal.

However, the class Contactwill be expanded in the near future. Every time I add new properties / values ​​to the class, I have to add them to isEqualTo. There is nothing complicated, but a little cumbersome.

, isEqualTo ?

get_class_vars get_object_vars, , vars, .

get_class_methodes, , . get... set... , , , " " .

: "" PHP ?

+4
2

, "" , / / , php, / :

<?php
class Foo {
    private $x,$y,$z;
    public function __construct($x,$y,$z) {
        $this->x = $x;
        $this->y = $y;
        $this->z = $z;
    }
}

$f1 = new Foo(1,2,3);
$f2 = new Foo(4,5,6);
$f3 = new Foo(1,2,3);

var_dump(
    $f1==$f2,
    $f1==$f3
);

bool(false)
bool(true)

.


Alma Do, , ,

<?php
class Foo {
    private $x,$y,$z;
    public function __construct($x,$y,$z) {
        $this->x = $x;
        $this->y = $y;
        $this->z = $z;
    }

    public function setZ($z) {
        $this->z = $z;
    }
}


$f1 = new Foo(1,2,3);
$f2 = new Foo(4,5,6);
$f3 = new Foo(1,2,3);

$f1->setZ($f3);
$f3->setZ($f1);


var_dump(
    $f1==$f2,
    $f1==$f3
);

Fatal error: Nesting level too deep - recursive dependency?.

+4

Reflection , , . , serialize() - ?

function isEquals(self $obj){
return serialize($obj)===serialize($this)
}
0

Source: https://habr.com/ru/post/1624067/


All Articles