只读属性

1 只读属性简介

只读属性的声明方式类似于普通属性,但需要使用 readonly 关键字。

2 只读属性例子

class Point {
public readonly float $x;
public readonly float $y;

public function __construct(float $x, float $y) {
$this->x = $x;
$this->y = $y;
}
}

$point = new Point(3.5, 2.8);
echo $point->x; // 输出: 3.5
echo $point->y; // 输出: 2.8

// 下面的尝试会导致致命错误,因为属性是只读的
$point->x = 5.0;