splfixedarray

SplFixedArray implements IteratorAggregate, ArrayAccess, Countable, JsonSerializable

定长数组:长度构造时固定(setSize 手动改)、只收整数键、未初始化槽为 NULL、内存紧凑——与普通 PHP 数组「自动增长、混合键、哈希桶开销」形成本质对照;越界读写抛 OutOfBoundsException。

C C23

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

int main(void) {
    size_t n = 3;
    char **f = malloc(n * sizeof(char *)); /* 一次 malloc 定长块 */
    f[0] = "red";
    f[1] = "green";
    f[2] = "blue";
    printf("%zu\n", n);   /* 3 */
    printf("%s\n", f[1]); /* green */
    /* 无越界检查:f[3] 会静默破坏内存——C 最经典的坑 */
    f = realloc(f, 4 * sizeof(char *)); /* 「扩容」= 搬到更大的块 */
    f[3] = NULL;
    printf("%zu\n", n + 1);        /* 4 */
    printf("%d\n", f[3] == NULL);  /* 新槽为 NULL */
    free(f);
    return 0;
}
输出
3
green
4
1

C++ C++26

C++26
#include <algorithm>
#include <array>
#include <iostream>
#include <string>

int main() {
    std::array<std::string, 3> f; // 长度是类型的一部分,编译期固定
    f[0] = "red";
    f[1] = "green";
    f[2] = "blue";
    std::cout << f.size() << "\n"; // 3
    std::cout << f[1] << "\n";     // green
    // f[3] = "x";                 // 编译错误:越界(at() 才会抛异常)
    // 「扩容」= 拷贝进更大的数组
    std::array<std::string, 4> g;
    std::copy(f.begin(), f.end(), g.begin());
    std::cout << g.size() << "\n";     // 4
    std::cout << g[3].empty() << "\n"; // 新槽默认为 ""
    return 0;
}
输出
3
green
4
1

C# v11.0.100

v11.0.100
using System;

var f = new string[3]; // 长度创建时固定
f[0] = "red";
f[1] = "green";
f[2] = "blue";
Console.WriteLine(f.Length); // 3
Console.WriteLine(f[1]);     // green
try {
    f[3] = "x";
} catch (IndexOutOfRangeException) {
    Console.WriteLine("IndexOutOfRangeException");
}
// 「扩容」= 新建数组并复制
Array.Resize(ref f, 4);
Console.WriteLine(f.Length);      // 4
Console.WriteLine(f[3] == null);  // 新槽默认为 null
输出
3
green
IndexOutOfRangeException
4
True

Go v1.27.4

v1.27.4
package main

import "fmt"

func main() {
	var f [3]string // 数组:长度是类型的一部分,编译期固定
	f[0] = "red"
	f[1] = "green"
	f[2] = "blue"
	fmt.Println(len(f)) // 3
	fmt.Println(f[1])   // green
	// f[3] = "x"       // 编译错误:越界(编译器直接拦截!)
	// 数组是值:赋值即整体拷贝
	g := f
	g[0] = "RED"
	fmt.Println(f[0], g[0]) // red RED
	// 切片是动态对照:make + append
	s := make([]string, 3)
	copy(s, f[:])
	s = append(s, "gold")
	fmt.Println(len(s)) // 4
	fmt.Println(s[3])   // gold
}
输出
3
green
red RED
4
gold

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        String[] f = new String[3]; // 长度创建时固定
        f[0] = "red";
        f[1] = "green";
        f[2] = "blue";
        System.out.println(f.length); // 3
        System.out.println(f[1]);     // green
        try {
            f[3] = "x";
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException");
        }
        // 「扩容」= 新建数组并拷贝
        String[] g = java.util.Arrays.copyOf(f, 4);
        System.out.println(g.length);      // 4
        System.out.println(g[3] == null);  // 新槽默认为 null
    }
}
输出
3
green
ArrayIndexOutOfBoundsException
4
true

JavaScript v26.13.1

v26.13.1
// JS Array 天生动态;定长风味来自 TypedArray
const f = ["red", "green", "blue"];
console.log(f.length);   // 3
console.log(f[1]);       // green
f.push("gold");          // 数组自由增长
console.log(f.length);   // 4
console.log(f[3]);       // gold
console.log(f[9]);       // undefined:越界读不抛错
// TypedArray 才是定长、受检的风味
const t = new Uint8Array(3); // 三个字节,零填充,不可增长
t[0] = 65;
console.log(t.length);   // 3
console.log(t[0]);       // 65
输出
3
green
4
gold
undefined
3
65

PHP v8.6.0

v8.6.0
$f = new SplFixedArray(3);
$f[0] = "red";
$f[1] = "green";
$f[2] = "blue";
echo $f->getSize(), "\n";      // 3
echo $f[1], "\n";              // green
$f->setSize(4);                // 扩容:新槽默认为 NULL
echo $f->getSize(), "\n";      // 4
var_dump($f[3]);               // NULL
try {
    $f[4] = "x";
} catch (OutOfBoundsException $e) {
    echo "OutOfBoundsException: ", $e->getMessage(), "\n";
}
try {
    $f["name"] = "x";
} catch (TypeError $e) {
    echo "TypeError: string keys not allowed\n";
}
输出
3
green
4
NULL
OutOfBoundsException: Index invalid or out of range
TypeError: string keys not allowed

Python v3.15.2

v3.15.2
# Python 核心无原生定长数组;list 动态且越界受检
f = ["red", "green", "blue"]
print(len(f))          # 3
print(f[1])            # green
f.append("gold")       # 列表自由增长
print(len(f))          # 4
print(f[3])            # gold
try:
    f[4] = "x"
except IndexError:
    print("IndexError")  # 越界写入仍报错
# array.array 给紧凑定类型存储,但长度依然动态
import array
a = array.array("i", [10, 20, 30])
print(len(a))          # 3
输出
3
green
4
gold
IndexError
3

Rust v1.99.1

v1.99.1
fn main() {
    // 长度是类型的一部分;越界是编译错误
    let mut f: [Option<&str>; 3] = [None; 3];
    f[0] = Some("red");
    f[1] = Some("green");
    f[2] = Some("blue");
    println!("{}", f.len());          // 3
    println!("{}", f[1].unwrap());    // green
    // f[3] = Some("x");              // 编译错误:越界
    // 「扩容」= 移入更大的数组
    let mut g: [Option<&str>; 4] = [None; 4];
    g[..3].copy_from_slice(&f);
    println!("{}", g.len());          // 4
    println!("{}", g[3].is_none());   // 新槽为 None
    // Vec 是动态对照
    let mut v: Vec<&str> = vec!["red", "green", "blue"];
    v.push("gold");
    println!("{}", v.len());          // 4
}
输出
3
green
4
true
4

TypeScript v26.13.1

v26.13.1
// TS Array 动态;定长风味是元组类型
const f: string[] = ["red", "green", "blue"];
console.log(f.length);   // 3
console.log(f[1]);       // green
f.push("gold");
console.log(f.length);   // 4
console.log(f[3]);       // gold
console.log(f[9]);       // undefined:默认越界不报错
// 元组:长度由类型检查器强制
const t: [string, string, string] = ["red", "green", "blue"];
console.log(t.length);   // 3
输出
3
green
4
gold
undefined
3

语言差异说明

C:定长即一次 malloc 的块——无越界检查,f[3] 越界是静默内存破坏(C 最经典的坑);「扩容」=realloc 搬家。SplFixedArray 可视为「带越界检查的 malloc 块 + 整数键」。

C++:std::array<T, N> 长度即类型一部分,越界索引是编译错误(operator[] 运行时不查,at() 才抛 out_of_range)。

C#:数组定长,f[3] 抛 IndexOutOfRangeException;Array.Resize 实际是新建数组 + 复制(新引用经 ref 传回)。

Go:数组长度是类型一部分([3]string),越界编译错误;日常用切片(动态),且数组赋值是整体拷贝——示例 g := f 后改 g 不动 f。

Java:数组定长,运行时越界抛 ArrayIndexOutOfBoundsException;扩容 = Arrays.copyOf。

JavaScript:Array 天生动态,越界读得 undefined 不抛错;定长风味在 TypedArray(字节数固定,但越界写被静默忽略是另一坑)。

PHP:SplFixedArray 与普通数组的本质区别:长度构造时固定(setSize 手动改)、只收整数键(字符串键抛 TypeError,8.1 起)、未初始化槽为 NULL、内存紧凑(手册与用户实测:百万级元素省约四分之三内存);越界读写抛 OutOfBoundsException(8.4 起,此前是消息相同的 RuntimeException)。代价:多数 array_* 函数不适用,也不能用 [] 追加。

Python:核心无原生定长数组——list 动态且越界抛 IndexError;array.array 只给紧凑定类型存储,长度仍动态。

Rust:定长数组 [T; N] 越界是编译错误;示例槽位用 Option,新槽默认 None;动态对照 Vec::push。

TypeScript:定长风味在类型层——tuple [string, string, string] 编译期强制长度,运行时不拦(noUncheckedIndexedAccess 可收紧越界读)。