MarvinX MarvinX -3 years ago 132
PHP Question

Comparing two objects except the pdo var

for my php project, I've created group objects which should be compared. Because they have a PDO connection stored in a variable, the == operator will always return false because one variable is not equal. Is there a way to compare these objects except comparing this one unique PDO variable?
The only way I could imagine would be a huge for loop which checks each variable.
I would be very happy if someone knows a smarter way.

Answer Source

Use this function. It will use Reflection to compare every property except $exceptParameter

class Test
    public $var1;
    public $pdo;

    public function __construct($var1, $pdo)
        $this->var1 = $var1;
        $this->pdo = $pdo;
$a = new Test("test1", "test2");
$b = new Test("test1", "test3");
$c = new Test("test2", "test4");
function areSameExcept($obj1, $obj2, $exceptParameter) {
    $ref1 = new ReflectionClass($obj1);
    $ref2 = new ReflectionClass($obj2);

    $propertiesObj1 = $ref1->getProperties();

    foreach ($propertiesObj1 as $propertyObj1) {
        if ($propertyObj1->getName() === $exceptParameter) continue;
        $valueObj1 = $propertyObj1->getValue($obj1);

        $propertyObj2 = $ref2->getProperty($propertyObj1->getName());
        $valueObj2 = $propertyObj2->getValue($obj2);
        if ($valueObj1 !== $valueObj2) {
            return false;
    return true;
var_dump(areSameExcept($a, $b, "pdo")); // true
var_dump(areSameExcept($a, $c, "pdo")); // false
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download