字符串值语义

赋值之后改的是谁——PHP 字符串值语义与 10 语言字符串可变性对照。

C C23

C23
#include <stdio.h>
#include <string.h>

/* C 字符串是可变 char 缓冲、没有值语义:拷贝要手动 strcpy,
   strcat 原地写入 */
int main(void) {
    char s[] = "hello";
    char t[16];
    strcpy(t, s);
    strcat(t, " world");
    printf("%s\n", s);
    printf("%s\n", t);
    return 0;
}
输出
hello
hello world

C++ C++26

C++26
#include <cstdio>
#include <string>

// std::string 是值语义:赋值构造独立副本,
// 修改副本时原件不受影响
int main() {
    std::string s = "hello";
    std::string t = s;
    t += " world";
    std::printf("%s\n", s.c_str());
    std::printf("%s\n", t.c_str());
}
输出
hello
hello world

C# v11.0.100

v11.0.100
string s = "hello";
string t = s;   // 复制的是引用,不是对象
string u = s.ToUpperInvariant(); // 方法返回新字符串
Console.WriteLine(s);
Console.WriteLine(t);
Console.WriteLine(u);
t += " world";  // 字符串不可变:构造新对象
Console.WriteLine(t);
输出
hello
hello
HELLO
hello world

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strings"
)

// Go 字符串是不可变值:赋值共享底层指针,
// 但拼接总是构造全新字符串
func main() {
	s := "hello"
	t := s
	t += " world"
	u := strings.ToUpper(s)
	fmt.Println(s)
	fmt.Println(t)
	fmt.Println(u)
}
输出
hello
hello world
HELLO

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        String s = "hello";
        String t = s;   // 复制的是引用,不是对象
        String u = s.toUpperCase(); // 方法返回新字符串
        System.out.println(s);
        System.out.println(t);
        System.out.println(u);
        t += " world"; // 字符串不可变:构造全新对象
        System.out.println(t);
    }
}
输出
hello
hello
HELLO
hello world

JavaScript v26.13.1

v26.13.1
const s = "hello";
const t = s;          // 两个名字指向同一个不可变字符串
const u = s.toUpperCase(); // 方法返回新字符串
console.log(s);
console.log(t);
console.log(u);
let r = s;
r += " world"; // 构造新字符串;s 仍指向旧串
console.log(r);
输出
hello
hello
HELLO
hello world

PHP v8.6.0

v8.6.0
// PHP 字符串是值语义:赋值表现为完整拷贝,
// 修改一个变量永远不会透过另一个变量显形
$s = "hello";
$t = $s;          // 独立副本(COW 让它在写入前保持廉价)
$t .= " world";
echo $s, "\n";    // 不受影响

echo $t, "\n";

// 字符串函数返回新串;原串纹丝不动
$u = strtoupper($s);
echo $s, "\n";
echo $u, "\n";
输出
hello
hello world
hello
HELLO

Python v3.15.2

v3.15.2
s = "hello"
t = s          # 两个名字指向同一个不可变对象
u = s.upper()  # 方法返回新字符串
print(s)
print(t)
print(u)
r = s
r += " world" # 构造新对象;s 仍指向旧串
print(r)
输出
hello
hello
HELLO
hello world

Rust v1.99.1

v1.99.1
// String 拥有自己的字节;&str 是借用视图。赋值是移动,
// 独立副本必须用显式 clone 请求
fn main() {
    let s = String::from("hello");
    let mut t = s.clone();
    t.push_str(" world");
    println!("{}", s);
    println!("{}", t);
    let u = s.to_uppercase(); // 返回新 String
    println!("{}", u);
}
输出
hello
hello world
HELLO

TypeScript v26.13.1

v26.13.1
const s: string = "hello";
const t = s;              // 两个名字指向同一个不可变字符串
const u = s.toUpperCase(); // 方法返回新字符串
console.log(s);
console.log(t);
console.log(u);
let r = s;
r += " world"; // 构造新字符串;s 仍指向旧串
console.log(r);
输出
hello
hello
HELLO
hello world

语言差异说明

C:可变 char 缓冲(示例):字符串就是字符数组,strcpy/strcat 原地改写——既不可变性也没有值语义,拷贝与拼接全手动;缓冲区溢出一类错误的根源。

C++:值语义可变(示例):std::string 赋值即独立拷贝(拷贝构造),修改副本不影响原件——与 PHP 语义同款;实现可有 SSO(短串内联)优化,但语义上仍是独立值;C++17 的 string_view 是借用视图(近似 Rust &str)。

C#:不可变 + 引用(示例):string 是引用类型但内容不可变,赋值共享引用、任何「修改」构造新对象;驻留(interning)让相同字面量共享实例;StringBuilder 是拼接热路径的官方出口。

Go:不可变值(示例):字符串是「指针+长度」的不可变视图,赋值共享底层字节但无法改写;拼接总是分配新串;[]byte 与 string 互转需显式拷贝。

Java:不可变 + 驻留(示例):String 对象不可变,字面量驻留字符串池(相同字面量 == 相同对象);拼接编译器优化为 StringBuilder/invokedynamic;安全模型(String 作锁/路径/类名)依赖不可变性。

JavaScript:不可变 + 引擎驻留(示例):字符串原始值不可变,赋值共享同一对象;修改方法返回新串;引擎对相同字符串做内部化优化;拼接走 rope/cons-cell 优化,无需 StringBuilder。

PHP:值语义(示例):赋值表现为完整独立拷贝(zend_string 引擎层 COW:引用计数共享,写入时才真实分离——语义与性能解耦);字符串函数一律返回新串;没有驻留机制(字面量在编译期共享,运行期拼接各自分配);bytes 无编码语义(byte string)。

Python:不可变(示例):str 对象不可变,赋值共享同一对象;修改方法返回新串;小字符串驻留(interning)由解释器自动做(标识符式字面量);修改字符串请用列表 join 或 io.StringIO。

Rust:拥有 vs 借用(示例):String 是拥有字节的堆缓冲(可变),&str 是不可变借用视图——所有权模型让「共享可变字符串」编译不过;赋值是 move(原变量失效),独立副本必须显式 clone;to_uppercase 等返回新 String。

TypeScript:语言层与 JS 相同(示例):不可变字符串原始值 + 共享引用;类型系统层面 string 是原始类型(字面量类型可做单例类型:type Dir = "asc" | "desc"),readonly 修饰符可冻结对象形状但字符串本身已不可变。