类型属性是否支持可调用类型?

Is type callable supported with typed properties?

我为此搜索了原因,但找不到任何原因。

我尝试创建类型为 'callable' 的 属性。但是 PHP 给我一个致命错误 "cannot have type callable"。在 RFC 中,没有提到 callable 不是 属性 类型提示的允许类型。相反,有一些示例,其中使用 'callable' 作为类型化属性。

参见:https://wiki.php.net/rfc/typed-properties

这是什么原因?网上有关于这个话题的讨论吗?

提供的提案 link https://wiki.php.net/rfc/typed-properties 的状态为 已拒绝

在 php7.4 中 实施 的提议在这里 https://wiki.php.net/rfc/typed_properties_v2 并且有关于 callable 的解释:

The callable type is not supported, because its behavior is context dependent The following example illustrates the issue:

class Test {
    public callable $cb;

    public function __construct() {
        // $this->cb is callable here
        $this->cb = [$this, 'method'];
    }

    private function method() {}
}


$obj = new Test;
// $obj->cb is NOT callable here
($obj->cb)();

This means that it is possible to write a legal value to a property and then proceed to read an illegal value from the same property. This fundamental problem of the callable pseudo-type is laid out in much more detail in the consistent callables RFC.

The recommended workaround is to instead use the Closure type, in conjunction with Closure::fromCallable(). This ensures that the callable will remain callable independent of scope. For a discussion of alternative ways to handle the callable issue, see the Alternatives section.

php7.4 的所有已实施提案列表在此处 https://wiki.php.net/rfc#php_74.