10

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?

Rax Weber
  • 3,730
  • 19
  • 30
  • 4
    As a fast and loose answer: in your first sample you have three different "physical" `class` declarations, which become three different classes. In the second sample, you have only one `class`, and three instances of it. – deceze Oct 06 '16 at 09:10
  • @deceze You gave a good summary. Why not make it an answer? – Rax Weber Oct 06 '16 at 09:14
  • @chumkiu already did a good job of that. – deceze Oct 06 '16 at 09:16

1 Answers1

6

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.

Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
  • Yes I've read that, but check the `var_dump()` output of each instance, they are different. – Rax Weber Oct 06 '16 at 09:13
  • 3
    @Rax The `#1` after the class name is the *instance counter* (first instance of `class@anonymous`). The class name is identical in all cases. – deceze Oct 06 '16 at 09:15
  • Combining your answer and @deceze's gives me a clear view of it. Awesome. – Rax Weber Oct 06 '16 at 09:18