PHP 8.3 类型化类常量 - 闭包

问题描述 投票:0回答:1

本文 https://php.watch/versions/8.3/typed-constants#supported_types 确认 PHP 8.3 允许我们声明 Closure 类型的类型常量。

但我找不到任何关于如何做到这一点的参考。 这是一个错误,还是有可能将闭包作为常量?怎么办?

我尝试自己猜测语法,但没有结果:

class ClassWithTypedConstants
{
    public const int INTEGER = 1;
    public const int|string INTEGER_OR_STRING = 1;
    public const \Closure CLOSURE = () => {};
}
php syntax constants
1个回答
1
投票

const
关键字仅支持有限的表达式,但
define
函数支持任意表达式,因此您可以使用它先定义一个常量,然后将其分配给类常量。

define('CL', function () { echo "hello\n"; });

class Foo
{
    public const \Closure CL = CL;
}

这没有多大意义,我同意文章只是指出 Closure 是允许的类型。

顺便说一句,如果您尝试调用常量,则需要将其括在括号中。

(Foo::CL)();
© www.soinside.com 2019 - 2024. All rights reserved.