Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 561
Rax Weber Avatar asked Oct 06 '16 08:10

Rax Weber


People also ask

Does PHP support anonymous classes?

In PHP, an anonymous class is a useful way to implement a class without defining it. These are available from PHP 5.3 onwards. Anonymous classes are useful because: They are not associated with a name.

When to use anonymous class PHP?

Anonymous classes are useful when simple, one-off objects need to be created. All objects created by the same anonymous class declaration are instances of that very class. Note: Note that anonymous classes are assigned a name by the engine, as demonstrated in the following example.

Can anonymous classes have constructors PHP?

Anonymous classes were introduced into PHP 7 to enable for quick one-off objects to be easily created. They can take constructor arguments, extend other classes, implement interfaces, and use traits just like normal classes can.


1 Answers

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.

like image 179
Luca Rainone Avatar answered Nov 09 '22 01:11

Luca Rainone