您现在的位置是:自如初>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)
相关文章
- 使用 phpipze 编译扩展报错的解决方法
- PHP 7 特性之 匿名类
- PHP 8.2 新特性之 新增方法与弃用相关的操作
- PHP 8.2 新特性之 New Random Extension (新的随机数生成器扩展)
- PHP 8.2 新特性之 DNF Types
- PHP 8.2 新特性之 const 表达式中获取枚举的属性
- PHP 8.2 新特性之弃用动态属性
- PHP 8.2 新特性之 traits 中的常量
- PHP 8.2 新特性之 Hide Sensitive Information In The Back Traces
- PHP 8.2 新特性之 允许 null 和 false 作为独立类型