只读属性

不可变性的光谱——PHP 8.1 readonly 与 10 语言「谁在何时阻止改写」对照。

C C23

C23
#include <stdio.h>

/* C:const 成员阻止经该结构体改写(编译期强制) */
typedef struct {
    const int x;
    const int y;
} Point;

int main(void) {
    Point p = {3, 4}; /* 唯一的写入点:初始化器 */
    printf("%d\n", p.x + p.y);
    /* p.x = 10; */ /* 编译错误:向只读成员赋值 */
    return 0;
}
输出
7

C++ C++26

C++26
#include <cstdio>

// C++:const 成员只能写一次——仅限构造函数的成员初始化列表
class Point {
public:
    const int x;
    const int y;
    Point(int xx, int yy) : x(xx), y(yy) {} // 唯一合法写入点
};

int main() {
    Point p{3, 4};
    std::printf("%d\n", p.x + p.y);
    // p.x = 10; // 编译错误:向只读成员赋值
    return 0;
}
输出
7

C# v11.0.100

v11.0.100
var p = new Point { X = 3, Y = 4 };
Console.WriteLine(p.X + p.Y);
// p.X = 10; // 编译错误:init 属性只能在创建期赋值

class Point {
    // init 专用 setter(C# 9+):对象创建期可写,之后封死
    public int X { get; init; }
    public int Y { get; init; }
}
输出
7

Go v1.27.4

v1.27.4
package main

import "fmt"

// Go 没有 readonly:不可变靠约定——未导出字段 + getter 挡住包外,
// 但包内代码照写不误
type Point struct {
	x, y int // 未导出:包外不可见
}

func (p Point) Sum() int { return p.x + p.y } // 只读访问

func main() {
	p := Point{x: 3, y: 4} // 同包代码仍可自由写
	fmt.Println(p.Sum())
}
输出
7

Java v27.0.1

v27.0.1
public class Main {
    // final 字段:只赋值一次,编译器强制
    static class Point {
        final int x;
        final int y;
        Point(int x, int y) { this.x = x; this.y = y; }
    }

    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p.x + p.y);
        // p.x = 10; // 编译错误:不能向 final 变量赋值
    }
}
输出
7

JavaScript v26.13.1

v26.13.1
"use strict";
// JS 没有 readonly 语法:Object.freeze 是运行期锁——错误只在真正写入时
// 出现(严格模式下)
const p = Object.freeze({ x: 3, y: 4 });
console.log(p.x + p.y);

try {
  p.x = 10; // 非严格模式静默失败;严格模式抛 TypeError
} catch (e) {
  console.log("TypeError: " + e.message);
}
输出
7
TypeError: Cannot assign to read only property 'x' of object '#<Object>'

PHP v8.6.0

v8.6.0
class Point {
    public function __construct(
        public readonly int $x, // 提升参数 + readonly:只能写一次
        public readonly int $y,
    ) {}
}

$p = new Point(3, 4);
echo $p->x + $p->y, "\n";

try {
    $p->x = 10; // 二次写入:抛 Error,即使值相同也不行
} catch (Error $e) {
    echo "Error: ", $e->getMessage(), "\n";
}
输出
7
Error: Cannot modify readonly property Point::$x

Python v3.15.2

v3.15.2
class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

    @property
    def x(self):        # 只读属性:只有 getter 没有 setter
        return self._x

    @property
    def y(self):
        return self._y

p = Point(3, 4)
print(p.x + p.y)
try:
    p.x = 10            # 抛 AttributeError:属性 x 没有 setter
except AttributeError as e:
    print("AttributeError:", e)
输出
7
AttributeError: property 'x' of 'Point' object has no setter

Rust v1.99.1

v1.99.1
// Rust 不可变是默认:普通绑定编译期冻结;只有 let mut 可以再赋值——
// 运行期无需任何检查
fn main() {
    let x = 3;
    let y = 4;
    println!("{}", x + y);

    // x = 10; // 编译错误:不能对不可变变量二次赋值
    let mut m = 1;
    m = 10; // 显式选择可变后可用
    println!("{}", m);
}
输出
7
10

TypeScript v26.13.1

v26.13.1
// TS readonly:纯编译期修饰符——转译为 JS 后消失;
// 它保护的是代码库,不是运行时
class Point {
  readonly x: number;
  readonly y: number;
  constructor(x: number, y: number) {
    this.x = x; // 唯一合法写入点
    this.y = y;
  }
  sum(): number {
    return this.x + this.y;
  }
}

const p = new Point(3, 4);
console.log(p.sum());
// p.x = 10; // 编译错误:不能给 readonly 属性赋值
输出
7

语言差异说明

C:struct 的 const 成员(示例):仅初始化器可写一次,编译期拦截后续赋值;「对象图」级深不可变需逐成员 const。

C++:const 成员只能在构造函数初始化列表写一次(示例);编译期约束;整个对象只读用 const Point& / const Point* 传递。

C#:两件套——字段级 readonly(构造器可写)+ 属性级 init 访问器(C# 9+,对象创建期可写,示例);编译期约束;record + with 表达式生成新对象而非改旧对象。

Go:无 readonly——不可变靠约定:未导出字段 + getter 挡住包外(示例),包内照写不误;标准库无冻结机制。

Java:final 字段(示例):构造器写一次,编译期强制;无「运行期冻结对象图」内建,深层不可变需不可变类设计。

JavaScript:无 readonly 语法——Object.freeze 是运行期锁(示例):严格模式下改写抛 TypeError、非严格静默失败;浅冻结,深层需递归。

PHP:8.1+ readonly 属性(示例):初始化后二次赋值抛 Error(值相同也不行);只允许带类型的属性;8.2 有 readonly class;8.3 __clone 可重初始化;8.4 起隐式 protected(set);8.6 起允许声明默认值;注意「内部可变性」——属性存的对象自身仍可改。

Python:无 readonly——惯例是 _x 私有约定 + @property 只读 getter(示例):赋值触发 AttributeError;约定层防护,p._x = 10 仍可绕过。

Rust:不可变是默认(示例):普通绑定编译期冻结,let mut 显式选择可变;所有权系统顺带保证没有别名可变引用,不可变比多数语言更彻底。

TypeScript:readonly 修饰符纯编译期(示例):转译后消失,运行时无防护(要运行期锁回到 Object.freeze);保护的是团队代码库而非内存。