萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實現雙模式訪問陣列:同時支援 $arr['key'] 與 $obj->key 的三種方案

需求場景

希望同一個數據結構既能像陣列一樣 $data['x'] 訪問,又能像對象一樣 $data->x 訪問,且修改同步生效。這在配置對象、DTO、API 響應封裝中極其常見。

方案一:實現 ArrayAccess + 魔術方法 __get/__set(完全可控)

<?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

方案一運行結果

方案二:原生 ArrayObject + ARRAY_AS_PROPS 標誌(一行代碼)

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

方案二運行結果

方案三:匿名類快速構建(PHP 7.0+,適合臨時用)

$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 編碼需實現 JsonSerializablejson_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。
  • 現代 PHP:優先考慮 readonly class + 結構化數據,避免動態屬性帶來的維護陷阱。
copyright © 萬盛學電腦網 all rights reserved