PHP RFC: Typed Properties 2.0 通过,PHP 7.4 新特性 类属性的类型声明

随着标量类型和返回类型的引入,PHP 7 大大增强了 PHP 类型系统的功能。 但是,目前无法为类属性声明类型,从而迫使开发人员使用 getter 和 setter 方法来强制执行类型契约。 这要求了不必要的样板,使得使用不那么符合人体工程学的方式,并且对性能有不好影响。 此 RFC 通过引入对类属性类型声明的支持来解决该问题。

此前,

class User {
    /** @var int $id */
    private $id;
    /** @var string $name */
    private $name;

    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }

    public function getId(): int {
        return $this->id;
    }
    public function setId(int $id): void {
        $this->id = $id;
    }

    public function getName(): string {
        return $this->name;
    }
    public function setName(string $name): void {
        $this->name = $name;
    }
}

现在,

class User {
    public int $id;
    public string $name;

    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }
}

详情: https://wiki.php.net/rfc/typed_properties_...

癞蛤蟆想吃炖大鹅
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!