类型属性是否支持可调用类型? [英] Is type callable supported with typed properties?

查看:93
本文介绍了类型属性是否支持可调用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了原因,但找不到任何原因.

I searched reasons for this but wasn't able to find any reason for this.

我尝试创建一个类型为callable"的类型化属性.但是 PHP 给了我一个致命错误不能有可调用的类型".在 RFC 中,没有提到 callable 不是属性类型提示所允许的类型.取而代之的是一些示例,其中将可调用"用于类型化属性.

I tried to create a typed property with the type 'callable'. But PHP gives me a fatal error "cannot have type callable". In the RFC, it is not mentioned, that callable is not an allowed type for the property type hints. Instead there are examples, where the use of 'callable' for typed properties are used.

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

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

What is the reason for this? Are there any discussions on this topic online?

推荐答案

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

Proposal in provided link https://wiki.php.net/rfc/typed-properties has status declined.

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

The proposal implemented in php7.4 is here https://wiki.php.net/rfc/typed_properties_v2 and there's an explanation about 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)();

这意味着可以将合法值写入属性然后继续从同一属性中读取非法值.这callable 伪类型的基本问题有很多一致可调用文件 RFC 中的更多详细信息.

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.

推荐的解决方法是改用 Closure 类型,在与 Closure::fromCallable() 结合使用.这确保了callable 将保持可调用独立于范围.讨论处理可调用问题的替代方法,请参阅 Alternatives部分.

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.

List of all implemented proposals for php7.4 is here https://wiki.php.net/rfc#php_74.

这篇关于类型属性是否支持可调用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆