Cannot use anonymous class in constant expression
Description
PHP 8.1’s “new in initializers” allows object-creation expressions to appear in constant-expression contexts, such as default parameter values, property defaults, static variables, class constants and attribute arguments, as long as the class being instantiated is fixed and unambiguous. An anonymous class is declared and compiled at the exact spot it is written; allowing one inside a shared, deferred context like a property default would raise questions about when and how often it actually gets declared, so it remains disallowed there.
Example
<?php
class Foo {
public $bar = new class {};
}
?>
Alternatives
- Give the class a name, declare it separately, and use new Name(…) in the constant expression instead.
Related error messages
- cannot-use-dynamic-class-name-in-constant-expression
- static-“-is-not-allowed-in-compile-time-constants
Changed Behavior
This error may appear following an evolution in behavior, in previous versions. See