L
L
lawyer_of_a_devil2014-07-28 10:17:07
PHP
lawyer_of_a_devil, 2014-07-28 10:17:07

Is there a pattern for comparing two objects (PHP)?

For example, I want to compare two objects $apple1 and $apple2 and understand that they have differences:

$apple1 = new stdClass();
$apple1->color = red;
$apple1->size = 30;
//...

$apple2 = new stdClass();
$apple2->color = green;
$apple2->size = 30;
//..

Comparison of course is carried out by properties.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-07-28
@lawyer_of_a_devil

If you just need to compare objects for equality, == will do the trick . If you need to get the differences between two objects, you can do this:

<?php

$a = (object) ['color' => 'red', 'foo' => 'bar'];
$b = (object) ['color' => 'green', 'foo' => 'bar'];

$diff = array_diff(get_object_vars($a), get_object_vars($b));

You can also make a diff method for the class that takes another argument ... It all depends on the task.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question