Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 8.3 Typed Class Constants - Closures

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 = () => {};
}
like image 704
Web-Fu Avatar asked Oct 27 '25 19:10

Web-Fu


1 Answers

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)();
like image 114
shingo Avatar answered Oct 29 '25 12:10

shingo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!