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(…) 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;};
}

?>

Alternatives

  • 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