Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Every Anonymous Class Is Different

<?php

print get_class($c = new class() {});
//class@anonymousphp-wasm run script:3$0
$d = new class() {};

var_dump($c instanceof $d);
// false!

interface i {}

$e = new class() implements i {};
var_dump($e instanceof i);
// true

function foo() {
    return new class() {};
}
$x = foo();
var_dump(foo() instanceof $x);
// syntax error !
// var_dump($x instanceof foo());

?>

Anonymous classes don’t have an explicit name, yet PHP uses one internally. That name is build on top of the localisation of the class definition in the code.

This means that two anonymous class objects (sic), created with the same code, but at different places in the code, are considered of a different type by PHP.

On the other hand, when the same piece of code produces the anonymous class object, it is considered of the same class.

Note that the syntax foo() instanceof $x is valid, but $x instanceof foo() is not. The second operand of instanceof is a bit precious, and forbid many expressions: this is the case of a simple assignation.

See Also

PHP Features

Last updated: 10 September 2026