Rax Weber
Rax Weber

Reputation: 3780

PHP 7 - Comparing Anonymous Class Instances

I have tried this code:

$ac1 = new class {};
$ac2 = new class {};

var_dump($ac1); // object(class@anonymous)#1 (0) {}
var_dump($ac2); // object(class@anonymous)#2 (0) {}
var_dump(new class {}); // object(class@anonymous)#3 (0) {}

var_dump($ac1 == $ac2); // bool(false)
var_dump($ac1 == new class {}); // bool(false)
var_dump($ac2 == new class {}); // bool(false)

The result of the above comparisons are all false.

However, when I declare a function that returns an anonymous class, this is the result:

function anonymous_class() {
    return new class {};
}

$ac1 = anonymous_class();
$ac2 = anonymous_class();

var_dump($ac1); // object(class@anonymous)#1 (0) {}
var_dump($ac2); // object(class@anonymous)#2 (0) {}
var_dump(anonymous_class()); // object(class@anonymous)#3 (0) {}

var_dump($ac1 == $ac2); // bool(true)
var_dump($ac1 == anonymous_class()); // bool(true)
var_dump($ac2 == anonymous_class()); // bool(true)

All printed true.

Now, the question is, how did that happen? Particularly, why did it print true for the second context, knowing that each var_dump() of the instances resulted differently?

Upvotes: 10

Views: 408

Answers (1)

Luca Rainone
Luca Rainone

Reputation: 16458

From doc http://php.net/manual/en/language.oop5.anonymous.php

All objects created by the same anonymous class declaration are instances of that very class.

<?php
function anonymous_class()
{
    return new class {};
}

if (get_class(anonymous_class()) === get_class(anonymous_class())) {
    echo 'same class';
} else {
    echo 'different class';
}

The above example will output: same class

And from http://php.net/manual/en/language.oop5.object-comparison.php

When using the comparison operator ==, object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with ==), and are instances of the same class.

Upvotes: 6

Related Questions