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 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.

Changed Behavior

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