您现在的位置是:自如初>PHP基础PHP基础

PHP8.1新特性之Readonly Properties(只读属性)

温新 2022-02-10 20:55:56 PHP基础 1495人已围观

简介PHP8.1新特性之Readonly Properties(只读属性)

只读属性必须要有类型限制;

只读属性只能在构造函数中初始化赋值;

只读属性不能有默认值


构造函数中赋值

<?php

class
Person

{
    public function __construct(
       // 变量的类型必须进行设置
       // 否则会报错
       public readonly string $name,
       public readonly int $age,
     )
    {
    }
}

$person = new Person('lucy', 18);
echo $person->name, $person->age;

声明再赋值

<?php

class Person

{
    public readonly string $name;
    public readonly int $age;

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

$person = new Person('lucy', 18);
echo $person->name, $person->age;

对只读属性设置默认值会报错

<?php

class
Person

{
    public readonly string $name = 'lucy';
    public readonly int $age;

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

$person = new Person('lucy', 18);
echo $person->name, $person->age;

报错信息:Fatal error: Readonly property Person::$name cannot have default value in

很赞哦!(15)

文章评论

登录 注册

自如初--时间轴

站名:自如初

独白:向前走!向前走!

邮箱:ziruchu@qq.com

RSS: RSS

站点信息