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

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.

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See