希望同一個數據結構既能像陣列一樣 $data['x'] 訪問,又能像對象一樣 $data->x 訪問,且修改同步生效。這在配置對象、DTO、API 響應封裝中極其常見。
<?php
class ArrayObjectProxy implements ArrayAccess {
private array $data = [];
public function __construct(array $data = []) {
$this->data = $data;
}
// ArrayAccess 接口四大方法
public function offsetExists(mixed $offset): bool {
return isset($this->data[$offset]);
}
public function offsetGet(mixed $offset): mixed {
return $this->offsetExists($offset) ? $this->data[$offset] : null;
}
public function offsetSet(mixed $offset, mixed $value): void {
if ($offset === null) {
$this->data[] = $value;
} else {
$this->data[$offset] = $value;
}
}
public function offsetUnset(mixed $offset): void {
if ($this->offsetExists($offset)) {
unset($this->data[$offset]);
}
}
// 對象屬性訪問代理到陣列
public function __get(string $name): mixed {
return $this->offsetGet($name);
}
public function __set(string $name, mixed $value): void {
$this->offsetSet($name, $value);
}
public function __isset(string $name): bool {
return $this->offsetExists($name);
}
public function __unset(string $name): void {
$this->offsetUnset($name);
}
// 可選:轉回原生陣列
public function toArray(): array {
return $this->data;
}
}
$data = ['x' => 'x', 'y' => 'y'];
$obj = new ArrayObjectProxy($data);
// 陣列讀寫
echo $obj['x']; // x
$obj['x1'] = 'x1';
echo $obj->x1; // x1 (陣列寫入,對象讀取同步)
// 對象讀寫
$obj->y1 = 'y1';
echo $obj['y1']; // y1 (對象寫入,陣列讀取同步)
// 輸出:
// 陣列方式訪問($obj['x'])輸出:x
// 對象方式訪問($obj->y)輸出:y
// 陣列方式賦值$obj['x1']='x1'
// 對象方式訪問($obj->x1)輸出:x1
// 對象方式賦值$obj->y1='y1'
// 陣列方式訪問($obj['y1'])輸出:y1

PHP 內建 ArrayObject 類配合旗標即可實現同樣效果:
$data = ['x' => 'x', 'y' => 'y'];
$obj = new ArrayObject($data, ArrayObject::ARRAY_AS_PROPS);
echo $obj['x']; // x
echo $obj->y; // y
$obj['x1'] = 'x1';
echo $obj->x1; // x1
$obj->y1 = 'y1';
echo $obj['y1']; // y1

$data = ['x' => 'x', 'y' => 'y'];
$obj = new class($data) extends ArrayObject {
public function __construct(array $data) {
parent::__construct($data, ArrayObject::ARRAY_AS_PROPS);
}
// 可在此擴展自定義方法
public function toJson(): string {
return json_encode($this->getArrayCopy());
}
};
echo $obj->toJson(); // {"x":"x","y":"y"}
| 維度 | 方案一:手寫 ArrayAccess | 方案二:ArrayObject | 方案三:匿名類 |
|---|---|---|---|
| 代碼量 | ~40 行 | 1 行 | ~10 行 |
| 可定制性 | 最高(可加驗證、事件、日誌) | 中(可繼承擴展) | 高(可內聯邏輯) |
| 性能 | 略低(用戶態方法調用) | 最高(C 級實現) | 同方案二 |
| 序列化 | 需實現 Serializable | 原生支援 | 原生支援 |
| JSON 編碼 | 需實現 JsonSerializable | json_encode 直接支援 | 直接支援 |
| 推薦場景 | 領域模型、表單對象、需業務邏輯 | 通用配置、快速原型、數據傳輸 | 一次性腳本、閉包內部、測試代碼 |
PHP 8.1+ 可用 readonly 修飾符構建不可變值對象:
readonly class Config {
public function __construct(
public string $appName,
public int $maxConnections,
public array $features = []
) {}
}
$cfg = new Config('MyApp', 100, ['cache' => true]);
// $cfg->appName = 'Other'; // Error: Cannot modify readonly property
// 但無法直接用 $cfg['appName'],需搭配 ArrayObject 或實現 ArrayAccess
new ArrayObject($data, ArrayObject::ARRAY_AS_PROPS)。ArrayAccess + __get/__set。readonly class + 結構化數據,避免動態屬性帶來的維護陷阱。