PHP8.1新特性之Readonly Properties(只读属性)
只读属性必须要有类型限制;
只读属性只能在构造函数中初始化赋值;
只读属性不能有默认值
构造函数中赋值
class Person
{
public function __construct(
// 变量的类型必须进行设置
// 否则会报错
public readonly string $name,
public readonly int $age,
)
{
}
}
$person = new Person('lucy', 18);
echo $person->name, $person->age;
声明再赋值
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;
对只读属性设置默认值会报错
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
请登录后再评论