Closures in constant expressions must be static

Description

When defining a closure as a constant value, there cannot be any context value that are imported. This includes the current object $this which is included by default in any closure. To avoid this, the static option must be added to the closure.

Example

<?php

class X {
    const MY = function () { return 1;}
}

?>

Solutions

  • Add the static option to the closure.

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