PHP 8.1 中只读的好处是什么?
What is the benefit of readonly in PHP 8.1?
readonly
现在可以在 PHP 8.1 中使用了,我只是想知道它有什么用?是帮助编辑知道这个 属性 只是 readonly
还是帮助客户知道那个还是有其他好处?
readonly
属性允许您创建不可变对象,或者至少是不可变属性。
这样您就可以确保在对象的整个生命周期中,初始化后的值不会被意外更改。
它与常量(通过 const
或 define
设置)的概念非常相似,尽管有两个重要区别:
- 常量需要在“编译”时定义,而
readonly
属性将在运行时设置,通常在对象实例化期间设置(因此多个实例将能够保存不同的值*)
- 与存在于全局范围内的常量相反,在 class 常量的情况下,它们的值与 class 而不是实例相关联。
您 可以 使用只能通过 getter 访问的私有 属性 实现相同的效果。例如,在“过去的日子”中:
class Foo {
private DateTimeImmutable $createAt;
public function __construct() {
$this->createdAt = new DateTimeImmutable();
}
public getCreatedAt(): DateTimeImmutable
{
return $this->createdAt;
}
}
$f = new Foo();
echo $f->getCreatedAt()->format('Y-m-d H:i:s');
唯一的问题是它需要大量样板代码。
与PHP 8.1。同样可以通过这样做来实现:
class Foo
{
public function __construct(
public readonly DateTimeImmutable $createdAt = new DateTimeImmutable()
)
{ }
}
$f = new Foo();
echo $f->createdAt->format('Y-m-d H:i:s')
readonly
现在可以在 PHP 8.1 中使用了,我只是想知道它有什么用?是帮助编辑知道这个 属性 只是 readonly
还是帮助客户知道那个还是有其他好处?
readonly
属性允许您创建不可变对象,或者至少是不可变属性。
这样您就可以确保在对象的整个生命周期中,初始化后的值不会被意外更改。
它与常量(通过 const
或 define
设置)的概念非常相似,尽管有两个重要区别:
- 常量需要在“编译”时定义,而
readonly
属性将在运行时设置,通常在对象实例化期间设置(因此多个实例将能够保存不同的值*) - 与存在于全局范围内的常量相反,在 class 常量的情况下,它们的值与 class 而不是实例相关联。
您 可以 使用只能通过 getter 访问的私有 属性 实现相同的效果。例如,在“过去的日子”中:
class Foo {
private DateTimeImmutable $createAt;
public function __construct() {
$this->createdAt = new DateTimeImmutable();
}
public getCreatedAt(): DateTimeImmutable
{
return $this->createdAt;
}
}
$f = new Foo();
echo $f->getCreatedAt()->format('Y-m-d H:i:s');
唯一的问题是它需要大量样板代码。
与PHP 8.1。同样可以通过这样做来实现:
class Foo
{
public function __construct(
public readonly DateTimeImmutable $createdAt = new DateTimeImmutable()
)
{ }
}
$f = new Foo();
echo $f->createdAt->format('Y-m-d H:i:s')