Categories
未分类

PHP 8 新特性:从构造函数直接声明属性

在 PHP 8 之前,自定义的类中,对于一个属性的初始化和使用过程是这样的。如下:

<?php
class User {
    private $name;
    public function __construct($name) {
        $this->name = $name;
    }
    public function getName() {
        return $this->name;
    }
}

$user = new User("chao");
printf("User's name: %s\n", $user->getName());
// 输出:User's name: chao

在 PHP 8 之后,我们可以直接在构造函数中将入参声明为类属性,并指明访问权限和变量类型。如下:

<?php
class User {
    public function __construct(private string $name) {
    }
    public function getName() {
        return $this->name;
    }
}

$user = new User("chao");
printf("User's name: %s\n", $user->getName());
// 输出:User's name: chao

通过代码“__construct(private string $name)”,声明了属性变量 name,指明访问权限为 private,类型为 string。当通过构造函数构建实例时,直接对 name 进行了赋值。

(完)

扫码阅读和分享

Leave a Reply

Your email address will not be published. Required fields are marked *