static“ is not allowed in compile-time constants
Description
“New in initializers” (PHP 8.1) allows new expressions in constant-expression contexts, such as default parameter values, as long as the class being instantiated is fixed and unambiguous: a literal class name, self, or parent. static refers to the class actually used at call time (late static binding), which can differ for every subclass, so it cannot be resolved once and for all at the point the initializer is compiled, and is rejected.
Example
<?php
class Point {
public function __construct(
public readonly self $origin = new static()
) {}
}
?>
Alternatives
- Use self if the intent is to always instantiate the declaring class.
- Move the instantiation into the constructor or method body instead, where late static binding works normally: $origin ??= new static();
Related error messages
- static::-“-is-not-allowed-in-compile-time-constants
- static::class-cannot-be-used-for-compile-time-class-name-resolution
- cannot-use-dynamic-class-name-in-constant-expression
- cannot-use-anonymous-class-in-constant-expression
Changed Behavior
This error may appear following an evolution in behavior, in previous versions. See