Alana Storm
Alana Storm

Reputation: 166086

PHP Object Equality for Nested Objects

Is there any stand alone code, or a library in a stand alone framework that can be used for comparing PHP objects that contain other object references?

The equality operator can be used to test object identity. I'm looking for code that would let me do something like this

$a = new Foo;
$b = new Foo;

if(objectsAreEqual($a,b)
{
}

I know I could use something like this

get_object_vars($a) == get_object_vars($b)

or some other form of reflection to compare properties, but if the object contains a nested object, we're back to the identity problem.

So, before I attempt to implement myself, I've like to know is this is a solved problem anywhere

Upvotes: 2

Views: 691

Answers (1)

Ivan Pintar
Ivan Pintar

Reputation: 1881

I don't think there is a way to do this without recursion:

function objectsAreEqual($a, $b) {
    $aProps = get_object_vars($a);
    $bProps = get_object_vars($b);


    foreach($aProps as $k => $v) {
        // check if key exists in b
        if(!isset($bProps[$k]) { 
            return false; 
        }

        // check if they're equal (if not an object or array)
        if($v != $bProps[$k]) {
            return false;
        }

        // if $v is an object or array
        if(is_object($v) || is_array($v)) {
            return objectsAreEqual($v, $bProps[$k]);
        }  

    }   

    return true;
}

Be sure to test this, but I think it should work. If you need to fix it before it works, please edit the code here too.

Upvotes: 2

Related Questions