This article https://php.watch/versions/8.3/typed-constants#supported_types affirms that PHP 8.3 allows us to declare typed constants of Closure type.
But I could not find any reference on how to do it. Is it a mistake, or is there the possibility to have closures as constants? How can it be done?
I tried to guess the syntax on my own, but with no results:
class ClassWithTypedConstants
{
public const int INTEGER = 1;
public const int|string INTEGER_OR_STRING = 1;
public const \Closure CLOSURE = () => {};
}
The const
keyword only supports limited expressions, but the define
function supports arbitrary expressons, so you can use it to define a constant first and then assign it to a class constant.
define('CL', function () { echo "hello\n"; });
class Foo
{
public const \Closure CL = CL;
}
This doesn't make much sense, I agree with the article just pointing out that Closure is an allowed type.
BTW if you try to invoke the constant, you need to wrap it in parenthesis.
(Foo::CL)();