php实现struct
在PHP中,没有内置的struct数据结构(如C语言中的struct),但可以通过以下方法模拟类似功能:
使用关联数组
关联数组可以模拟键值对的结构,类似于struct的字段存储:
$person = [
'name' => 'John',
'age' => 30,
'is_active' => true
];
echo $person['name']; // 输出: John
使用stdClass对象
通过stdClass创建匿名对象,动态添加属性:
$person = new stdClass();
$person->name = 'John';
$person->age = 30;
echo $person->name; // 输出: John
定义类
通过自定义类实现强类型结构,推荐使用PHP 7.4+的类型属性:
class Person {
public string $name;
public int $age;
public bool $is_active;
public function __construct(string $name, int $age, bool $is_active) {
$this->name = $name;
$this->age = $age;
$this->is_active = $is_active;
}
}
$person = new Person('John', 30, true);
echo $person->name; // 输出: John
使用数组解构(PHP 7.1+)
通过list()或短数组解构语法快速提取数据:
$data = ['John', 30, true];
[$name, $age, $isActive] = $data;
echo $name; // 输出: John
类型化属性(PHP 7.4+)
结合构造函数属性提升简化代码:
class Person {
public function __construct(
public string $name,
public int $age,
public bool $is_active
) {}
}
$person = new Person('John', 30, true);
选择方法时需考虑:

- 简单数据存储用关联数组或
stdClass - 需要类型检查和封装时用自定义类
- PHP 8.0+可结合
readonly属性实现不可变结构






