Cannot use(…) variables in constant expression

Description

It is possible to have closures in a constant, since PHP 8.5. Such closure must be static, so that it does not include the current object with $this. It also cannot use the use clause, as the definition of the closure is outside an execution context: there are no available variables to import in the closure.

Example

<?php

class X {
    const MY = static function () use ($a) { return 1;};
}

?>

Solutions

  • Remove the use clause of the closure.

  • Move the closure inside a method.

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