萬盛學電腦網

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

PHP 陣列與物件互轉:遞迴轉換、JsonSerializable、類型安全與效能優化

PHP 陣列與物件互轉是 API 序列化、配置管理、ORM 資料映射、快取儲存的核心操作。本文深度解析 (array) 強制轉型、json_encode/decode、get_object_vars()、遞迴轉換函數、JsonSerializable 介面、PHP 8.1+ readonly/__serialize/__unserialize 現代機制,並提供生產級工具類。

核心轉換方式對比

方法陣列→物件物件→陣列巢狀處理私有屬性效能
(object)$arr✅ stdClass❌❌ 單層N/A極快
json_decode(json_encode($arr))✅ stdClass✅ (第2參數 true)✅ 遞迴✅ 公開屬性慢 (雙重編碼)
(array)$obj❌✅ 含私有/受保護 (特殊鍵名)❌ 單層✅ 但鍵名含 \0class\0prop快
get_object_vars($obj)❌✅ 僅公開/當前作用域可見屬性❌ 單層視可見性快
自訂遞迴函數✅ 可指定類別✅ 完全控制✅ 遞迴✅ 可存取中等
JsonSerializable❌✅ 完全自訂✅ 遞迴✅ 內部可存取快 (單次編碼)

遞迴轉換工具函數 (通用版)

<?php
/**
 * 將任意資料結構 (陣列/物件/標量) 深度轉為純陣列
 * - 物件實作 JsonSerializable 以其為準
 * - 物件未實作則用 get_object_vars (僅公開/可見屬性)
 * - 資源類型跳過
 * - 循環引用檢測 (PHP 8.1+ 可用 WeakMap)
 */
function toArray(mixed $value, int $maxDepth = 512, array &$seen = []): mixed {
    if ($maxDepth <= 0) return '*DEPTH_LIMIT*';
    
    // 循環引用檢測 (物件/陣列)
    if (is_object($value) || is_array($value)) {
        $id = is_object($value) ? spl_object_id($value) : 'arr_' . spl_object_id($value); // 陣列無 spl_object_id,簡化處理
        if (isset($seen[$id])) return '*CIRCULAR_REF*';
        $seen[$id] = true;
    }
    
    if (is_array($value)) {
        $result = [];
        foreach ($value as $k => $v) {
            $result[$k] = toArray($v, $maxDepth - 1, $seen);
        }
        return $result;
    }
    
    if (is_object($value)) {
        // 1. 優先使用 JsonSerializable
        if ($value instanceof JsonSerializable) {
            return toArray($value->jsonSerialize(), $maxDepth - 1, $seen);
        }
        
        // 2. 使用 get_object_vars (需在類別內部或公開屬性)
        $vars = get_object_vars($value);
        $result = [];
        foreach ($vars as $k => $v) {
            $result[$k] = toArray($v, $maxDepth - 1, $seen);
        }
        return $result;
    }
    
    // 標量、null、資源直接返回
    return $value;
}

/**
 * 將陣列深度轉為指定類別物件 (需有無參建構子或支援屬性賦值)
 */
function toObject(array $array, string $className = 'stdClass', int $maxDepth = 512): object {
    if (!class_exists($className)) throw new InvalidArgumentException("Class $className not found");
    
    $obj = new $className();
    foreach ($array as $k => $v) {
        $val = is_array($v) ? toObject($v, $className, $maxDepth - 1) : $v;
        // 嘗試設定屬性 (公開或有 setter)
        if (property_exists($obj, $k)) {
            $obj->$k = $val;
        } elseif (method_exists($obj, 'set' . ucfirst($k))) {
            $obj->{'set' . ucfirst($k)}($val);
        } else {
            // 動態屬性 (PHP 8.2+ 棄用,stdClass 仍允許)
            $obj->$k = $val;
        }
    }
    return $obj;
}

JsonSerializable 介面:序列化完全控制 (推薦)

<?php
class User implements JsonSerializable {
    public function __construct(
        public int $id,
        public string $name,
        public string $email,
        private string $passwordHash, // 私有,不輸出
        public ?Address $address = null,
        public array $tags = [],
        public \DateTimeImmutable $createdAt
    ) {}
    
    public function jsonSerialize(): array {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'address' => $this->address, // 遞迴 jsonSerialize
            'tags' => $this->tags,
            'created_at' => $this->createdAt->format('c'), // 格式化日期
            // 故意排除 passwordHash
        ];
    }
}

class Address implements JsonSerializable {
    public function __construct(
        public string $city,
        public string $district,
        public string $street
    ) {}
    public function jsonSerialize(): array {
        return ['city' => $this->city, 'district' => $this->district, 'street' => $this->street];
    }
}

// 使用
$user = new User(1, 'Tom', 'tom@example.com', 'hash...', new Address('Taipei', 'DaAn', 'RenAi Rd'), ['vip'], new DateTimeImmutable());
echo json_encode($user, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
/*
{
    "id": 1,
    "name": "Tom",
    "email": "tom@example.com",
    "address": {"city": "Taipei", "district": "DaAn", "street": "RenAi Rd"},
    "tags": ["vip"],
    "created_at": "2024-01-15T10:30:00+08:00"
}
*/

PHP 8.1+ 現代序列化機制:__serialize / __unserialize

<?php
class DataTransferObject {
    public function __construct(
        public string $id,
        public array $payload,
        private string $internalToken // 不序列化
    ) {}
    
    // 自訂序列化資料 (替代 Serializable 介面,PHP 8.1+ 推薦)
    public function __serialize(): array {
        return [
            'id' => $this->id,
            'payload' => $this->payload,
            // 故意不包含 internalToken
        ];
    }
    
    // 自訂反序列化還原
    public function __unserialize(array $data): void {
        $this->id = $data['id'];
        $this->payload = $data['payload'];
        $this->internalToken = hash('sha256', $this->id . $this->payload); // 重新生成
    }
}

// 測試
$obj = new DataTransferObject('abc', ['key' => 'value'], 'secret');
$serialized = serialize($obj);
$restored = unserialize($serialized);
// $restored->internalToken 會是重新生成的雜湊,而非原始值

生產級 ArrayObjectTransformer 工具類

<?php
final class ArrayObjectTransformer {
    private int $maxDepth;
    private bool $includePrivate;
    private bool $useJsonSerializable;
    private array $typeCasters = []; // 類型轉換器 [ClassName => callable]
    
    public function __construct(array $options = []) {
        $this->maxDepth = $options['maxDepth'] ?? 512;
        $this->includePrivate = $options['includePrivate'] ?? false;
        $this->useJsonSerializable = $options['useJsonSerializable'] ?? true;
    }
    
    public function addTypeCaster(string $class, callable $caster): self {
        $this->typeCasters[$class] = $caster;
        return $this;
    }
    
    public function toArray(mixed $value): array {
        return $this->convert($value, []);
    }
    
    public function toObject(array $array, string $class = 'stdClass'): object {
        $obj = new $class();
        foreach ($array as $k => $v) {
            $val = is_array($v) ? $this->toObject($v, $class) : $v;
            $obj->$k = $val; // 依賴動態屬性或公開屬性
        }
        return $obj;
    }
    
    private function convert(mixed $value, array &$seen): mixed {
        if (is_array($value)) {
            $id = 'arr_' . spl_object_id($value); // 簡化,實際陣列無 ID 需用序列化雜湊
            if (isset($seen[$id])) return '*CIRCULAR*';
            $seen[$id] = true;
            
            $result = [];
            foreach ($value as $k => $v) {
                $result[$k] = $this->convert($v, $seen);
            }
            return $result;
        }
        
        if (is_object($value)) {
            $id = spl_object_id($value);
            if (isset($seen[$id])) return '*CIRCULAR*';
            $seen[$id] = true;
            
            // 自訂類型轉換器
            $class = get_class($value);
            if (isset($this->typeCasters[$class])) {
                return ($this->typeCasters[$class])($value);
            }
            
            // JsonSerializable
            if ($this->useJsonSerializable && $value instanceof JsonSerializable) {
                return $this->convert($value->jsonSerialize(), $seen);
            }
            
            // 反射取得所有屬性 (含私有)
            $props = [];
            $ref = new ReflectionObject($value);
            foreach ($ref->getProperties(ReflectionProperty::IS_PUBLIC | ($this->includePrivate ? ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE : 0)) as $prop) {
                $prop->setAccessible(true);
                $props[$prop->getName()] = $prop->getValue($value);
            }
            
            return $this->convert($props, $seen);
        }
        
        return $value;
    }
}

// 使用
$transformer = new ArrayObjectTransformer(['includePrivate' => true])
    ->addTypeCaster(DateTimeInterface::class, fn($dt) => $dt->format('c'))
    ->addTypeCaster(PDO::class, fn($pdo) => '*PDO_INSTANCE*');

$arr = $transformer->toArray($complexObject);

效能與記憶體考量

  • json_encode/decode:方便但雙倍記憶體 (原物件 + JSON 字串 + 解碼後物件),大物件慎用。
  • 遞迴函數:單次遍歷,記憶體增量小,但 PHP 函數呼叫開銷大。
  • 大量資料轉換:考慮分批、Generator、或直接操作原始陣列/物件避免轉換。
  • OPcache:JsonSerializable 回傳陣列會被 OPcache 優化,效能優於手動遞迴。

常見陷阱

循環引用導致無限遞迴/堆疊溢位
使用 spl_object_id() + WeakMap (PHP 8.0+) 追蹤已訪問物件。
私有屬性無法存取
(array)$obj 鍵名會變 "\0ClassName\0prop";用 ReflectionProperty::setAccessible(true) 或 get_object_vars() (需在類別作用域內)。
資源類型 (resource) 轉換失敗
資源無法序列化,轉陣列會變 null,JSON 編碼報錯。需預先轉為標識字串。
DateTime 物件 JSON 編碼格式不一致
實作 JsonSerializable 統一格式 (ISO 8601 c 或 DateTime::ATOM)。

陣列與物件互轉沒有銀彈,關鍵在於:定義清楚的資料邊界 (什麼該序列化)、選擇合適的序列化策略 (JsonSerializable 為首選)、處理邊界情況 (循環引用、資源、私有屬性)。封裝為可測試、可配置的 Transformer 服務,讓序列化邏輯集中管理、演進無痛!

copyright © 萬盛學電腦網 all rights reserved