类变量中的类型提示 [英] Type hinting in class variables

查看:71
本文介绍了类变量中的类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?php

namespace Sandbox;

class Sandbox {

    private Connectors\ISandboxConnector $connection;

    public function __construct(Connectors\ISandboxConnector $conn) {
        $this->connection = $conn;
    }

}

?>

对于上面的代码,我收到以下错误:

For the above code I'm getting the following error:

Parse error: syntax error, unexpected 'Connectors' (T_STRING), expecting variable (T_VARIABLE)

当我删除类型提示和var_dump该$ connection变量时,它将是private Sandbox\Sandbox而不是Sandbox\Connectors\ISandboxconnector,为什么?

When I remove the type hinting and var_dump that $connection variable, it will be private Sandbox\Sandbox and not Sandbox\Connectors\ISandboxconnector, why?

推荐答案

PHP 7.3及以下版本不支持类型化属性.您只能按如下方式定义变量:

PHP 7.3 and below does not support typed properties. You could only define a variable as below:

class Sandbox {
    private $connection;

但是,为了帮助编辑者理解您的代码,您可以使用

However, to help editors understand your code, you may use a @var tag to document the expected type of the property:

class Sandbox {
    /** @var Connectors\ISandboxConnector */
    private $connection;


更新

PHP 7.4.0


Update

PHP 7.4.0

感谢@Manuel提及新更新,PHP 7.4现在根据 PHP RFC:引入了类型化属性属性2.0 .

Thanks @Manuel for mentioning the new update, PHP 7.4 now introduces typed properties according to PHP RFC: Typed Properties 2.0.

属性类型声明支持PHP支持的所有类型声明,但voidcallable除外.还支持任何类或接口名称,stdClass,标量和复合类型,对父对象和自己对象的引用.

Property type declarations support all type declarations supported by PHP, with the exception of void and callable. Any class or interface name, stdClass, scalar and compound types, references to parent and own objects are also supported.

class Sandbox {
    public int $id;
    public string $name;
    private Connectors\ISandboxConnector $connection;
}

注意:注意未初始化状态和继承严格规则等副作用.

Note: keep an eye on side effects such as uninitialised state and inheritance strict rules.

这篇关于类变量中的类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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