Object casts are not supported in this context

Description

All cast operators are not supported in a static constant expression. This applies to all casts operations: (int), (string), (bool), (array), (object), until PHP 8.5. In PHP 8.5 and later, only (object) is not supported.

They look like any other operator, such as + or ., but they require data manipulations which are incompatible with constant expressions.

While it may be useless to apply a cast to a literal value, it might be useful to use it with another expression or another constant.

Example

<?php
class X {
    public $foo = (object) [];
}
?>

Solutions

  • Create a value directly with the target type.

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See ` <https://php-changed-behaviors.readthedocs.io/en/latest/behavior/.html>`_.