Cannot use dynamic class name in constant expression
Description
“New in initializers” (PHP 8.1) lets new SomeClass(…) appear in constant-expression contexts, such as default parameter values, but only when the class name is written literally, or via self/parent, something resolvable without evaluating an arbitrary expression. A dynamic class name taken from a variable or another expression cannot be resolved once and for all in that fixed, deferred context, so it is rejected at compile time.
Example
<?php
$className = 'DateTime';
class Bar {
public function baz($obj = new $className()) {}
}
?>
Alternatives
- Use a literal class name instead of a variable.
- Move the object creation into the function body instead of the parameter default.
Related error messages
- cannot-use-anonymous-class-in-constant-expression
- static::-“-is-not-allowed-in-compile-time-constants
- cannot-use–“::class-”-on-%s
- static-“-is-not-allowed-in-compile-time-constants
Changed Behavior
This error may appear following an evolution in behavior, in previous versions. See