[PHP-DEV] Object support in class constants

Hi all,

Somehow I missed that objects can be used in constants `const OBJ = new stdClass();` since PHP 8.1.

As this is allowed for constants, I don't understand why this is not allowed for class constants.

 class Test \{
     public const OBJ = new stdClass\(\); // Fatal error: New expressions are not supported in this context
 \}

While this works:

 const OBJ = new stdClass\(\);
 class Test \{
     public const OBJ = OBJ; // works
 \}

Is there are a reason for this limitation especially since "new" expression is valid for argument default values as well?

Thanks,
Marc

Is there are a reason for this limitation especially since “new”
expression is valid for argument default values as well?

From the RFC https://wiki.php.net/rfc/new_in_initializers#unsupported_positions

New expressions continue to not be supported in (static and non-static) property initializers and class constant initializers. The reasons for this are twofold:

For non-static property initializers, the initializer expression needs to be evaluated on each object creation. There are currently two places where this could happen: As part of object creation, and as part of the constructor call. Doing this as part of object creation can create issues for unserialization and any other process that is based on newInstanceWithoutConstructor() and does not want to implicitly execute potential side-effects.

Performing the initialization by injecting code in the constructor avoids the issue, but requires that constructor to actually be called. In particular, this would necessitate generating constructors for classes that do not explicitly declare them, and the disciplined invocation of such constructors from potential child constructors. The third option would be to introduce an additional initialization phase between creation and construction.

For static property initializers and class constant initializers a different evaluation order issue arises. Currently, these initializers are evaluated lazily the first time a class is used in a certain way (e.g. instantiated). Once initializers can contain potentially side-effecting expressions, it would be preferable to have a more well-defined evaluation order. However, the straightforward approach of evaluating initilizers when the class is declared would break certain existing code patterns. In particular, referencing a class that is declared later in the same file would no longer work.

As such support in these contexts is delayed until such a time as a consensus on the preferred behavior can be reached.