不对称可见性
读公开写受限——PHP 8.4 public private(set) 与 10 语言读写分离对照。
C C23
#include <stdio.h>
/* C 没有访问控制:任何拿到定义的代码都能读写结构体字段——
「私有」只靠命名约定(下划线后缀)和评审纪律维系 */
typedef struct {
int hits_;
} Counter;
void counter_record(Counter *c) { c->hits_++; }
int main(void) {
Counter c = {0};
counter_record(&c);
counter_record(&c);
printf("%d\n", c.hits_);
c.hits_ = 99; /* 没有任何东西阻止这一行——只有约定在反对 */
printf("%d\n", c.hits_);
return 0;
}
2 99
C++ C++26
#include <cstdio>
// C++ 私有字段把外部写入整个挡住:不存在读写分离,
// 所以公有 getter 加私有字段就是惯用法
class Counter {
public:
void record() { ++hits_; }
int hits() const { return hits_; }
private:
int hits_ = 0;
};
int main() {
Counter c;
c.record();
c.record();
std::printf("%d\n", c.hits());
// c.hits_ = 99; // 编译不过:hits_ 是私有的
}
2
C# v11.0.100
var c = new Counter();
c.Record();
c.Record();
Console.WriteLine(c.Hits);
// c.Hits = 99; // 编译不过:setter 是私有的
class Counter {
// 这正是 PHP 8.4 public private(set) 所镜像的模型
public int Hits { get; private set; } // 读公开、写私有
public void Record() { Hits++; }
}
2
Go v1.27.4
package main
import "fmt"
// Go 唯一的栅栏是包边界:未导出字段在包内任何地方都可写,
// 「包外可读、仅内部可写」没有直接对应物——
// 只有未导出字段加方法这一条路
type Counter struct {
hits int
}
func (c *Counter) Record() { c.hits++ }
func (c *Counter) Hits() int { return c.hits }
func main() {
c := &Counter{}
c.Record()
c.Record()
fmt.Println(c.Hits())
// c.hits = 99 // 包外编译不过
}
2
Java v27.0.1
public class Main {
static class Counter {
private int hits = 0; // 没有读写分离:私有字段加单个 getter
// 就是惯例
void record() { hits++; }
int hits() { return hits; }
}
public static void main(String[] args) {
Counter c = new Counter();
c.record();
c.record();
System.out.println(c.hits());
}
}
2
JavaScript v26.13.1
"use strict";
class Counter {
#hits = 0;
record() { this.#hits++; }
get hits() { return this.#hits; } // 只有 getter:未定义 setter
}
const c = new Counter();
c.record();
c.record();
console.log(c.hits);
try {
c.hits = 99; // 严格模式拒绝写入
} catch (e) {
console.log(e.constructor.name);
}
2 TypeError
PHP v8.6.0
class Counter {
// PHP 8.4 不对称可见性:读公开、写私有;
// 简写 private(set) 与 public private(set) 同义
public private(set) int $hits = 0;
public function record(): void {
$this->hits++; // 类内:允许写入
}
}
$c = new Counter();
$c->record();
$c->record();
echo $c->hits, "\n"; // 读取:任何地方都允许
try {
$c->hits = 99; // 类外写入 → Error
} catch (Error $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
2 Error: Cannot modify private(set) property Counter::$hits from global scope
Python v3.15.2
class Counter:
def __init__(self):
self._hits = 0 # 下划线 = 约定私有
def record(self):
self._hits += 1
@property
def hits(self): # 只读半边:未定义 @hits.setter
return self._hits
c = Counter()
c.record()
c.record()
print(c.hits)
try:
c.hits = 99
except AttributeError:
print("write rejected: read-only property")
2 write rejected: read-only property
Rust v1.99.1
// pub 字段遵循模块可见性;读写分离不存在,
// 所以惯用法是私有字段加访问器方法
struct Counter {
hits: i32,
}
impl Counter {
fn record(&mut self) { self.hits += 1; }
fn hits(&self) -> i32 { self.hits }
}
fn main() {
let mut c = Counter { hits: 0 };
c.record();
c.record();
println!("{}", c.hits());
}
2
TypeScript v26.13.1
"use strict";
class Counter {
#hits = 0;
record(): void { this.#hits++; }
get hits(): number { return this.#hits; } // 只有 getter:未定义 setter
}
const c = new Counter();
c.record();
c.record();
console.log(c.hits);
try {
c.hits = 99; // 严格模式拒绝写入
} catch (e) {
console.log((e as Error).constructor.name);
}
2 TypeError
语言差异说明
C:无访问控制(示例):结构体字段对任何持有定义的代码可读可写,「私有」只靠下划线命名约定维系;没有任何机制阻止外部直写。
C++:private 字段一刀切(示例):外部读写都被挡,getter 提供只读出口——「可读可写分离」要用 const 引用 getter + 私有字段模拟;没有「公开读、受限写」的字段级语法。
C#:{ get; private set; }(示例):PHP 8.4 不对称可见性的直接蓝本,语义逐字对应;C# 还支持 { get; protected set; } 与 init(仅初始化期可写);差别在 C# 读写走同一属性、PHP 的 set 可见性还能应用到虚属性/钩子上。
Go:导出粒度粗(示例):唯一栅栏是包边界,未导出字段包内全可写;「包外可读、包内可写」没有字段级支持,只能未导出字段 + 导出方法;粒度只有「包内/包外」两档。
Java:无语言级支持(示例):惯例是私有字段 + 单个 getter(省略 setter);没有「字段公开读、方法受限写」的语法——一切靠封装约定;Lombok @Getter(AccessLevel.NONE) 等属编译期生成。
JavaScript:getter-only 属性(示例):只定义 get 访问器时严格模式下赋值抛 TypeError、非严格静默失败——「半公开」行为依赖 strict 开关,语义上等价于「只读」而非「分级写」;没有 protected(set) 等中间档。
PHP:8.4+ 不对称可见性(示例):public private(set)/public protected(set)/protected private(set) 三档;set 可见性不得比主可见性更宽(protected public(set) 语法错误);简写 private(set) 等价 public private(set);private(set) 属性自动 final(子类不可重声明);8.5 起 set 可见性可应用于静态属性;取引用遵循 set 可见性(引用可绕过写检查)。
Python:@property 只读半边(示例):漏定义 setter 时赋值抛 AttributeError——得到的是「完全只读」而非「分级写」;没有语言级的 public-read/private-write 粒度,_ 前缀约定全靠自觉。
Rust:pub 字段模块粒度(示例):pub 字段在模块外可读可写,没有读写分离;「模块外只读」需要私有字段 + pub getter;粒度只有「模块内/模块外」两档,且 pub(crate)、pub(super) 只调栅栏位置不调读写方向。
TypeScript:语言层与 JS 相同的 getter-only 属性(示例):类型系统的 private/readonly 是编译期标记——readonly 字段只在声明/构造器可赋值(比「类内可写」更严),没有 protected(set) 等运行时分级;运行时行为与 JS 完全一致。