stdClass 是 PHP 內建的「空白類」,無任何屬性方法,卻是動態屬性容器、數組對象化、API 響應構建的利器。本文系統梳理其特性、三種創建方式、訪問模式、實例化陷阱與實戰模式。
$andy = ['a' => 1, 'b' => 2, 'c' => 3];
$andy = (object) $andy; // 或 (object)['a'=>1,...]
echo $andy->a; // 1
echo $andy->b; // 2
$a = new stdClass();
$a->id = '11';
$a->username = 'me';
print_r($a); // stdClass Object ( [id] => 11 [username] => me )
$json = '{"name":"John","age":30}';
$obj = json_decode($json); // 預設返回 stdClass
echo $obj->name; // John
// 強制關聯數組
$arr = json_decode($json, true);
$weather = json_decode($xmlResponse);
// 對象式訪問
$city = $weather->getWeatherbyCityNameResult->string[0]; // "四川"
// 若轉為數組
$weatherArr = json_decode($xmlResponse, true);
$city = $weatherArr['getWeatherbyCityNameResult']['string'][0];
對象語法更簡潔,數組語法更通用(支援 array_map 等函數式操作),按團隊習慣選擇。
$a = [1=>2, 2=>3];
$a = (object)$a; // 保留原數據
$a->id = '11';
print_r($a); // [1=>2, 2=>3, id=>11]
$b = [1=>2, 2=>3];
$b = (object)$b;
$b = new stdClass(); // 重新實例化,前序數據丟失!
$b->id = '11';
print_r($b); // [id=>11]
規則:new stdClass() 創建**全新實例**,之前轉型產生的對象被丟棄。只需 (object)$arr 或直接 new stdClass() 二選一。
function foo() {
global $obj;
$obj = &new stdClass(); // 錯誤:&new 已棄用且無效
// 正確:
$obj = new stdClass();
}
PHP 7+ 移除 &new,直接 new 即可,引用賦值由引擎自動處理。
/** @property string $name @property int $age */
class UserDTO extends stdClass {} // 僅為 IDE 提示,運行期仍是 stdClass
function processUser(UserDTO $user) {
echo $user->name;
}
$user = json_decode($json); // 實際是 stdClass
processUser($user); // 靜態分析通過,運行正常
利用「繼承 stdClass」欺騙 IDE/靜態分析工具,獲得屬性提示,運行期零成本。
| 場景 | 建議 |
|---|---|
| 臨時數據包、API 響應、配置對象 | ✅ stdClass 完美適配 |
| 需封裝業務邏輯、驗證、方法 | ❌ 必須定義具體類 |
| 高頻實例化、記憶體敏感 | ⚠️ 數組更輕量,或用 readonly class (PHP 8.1+) |
| 需序列化/反序列化 | ✅ 原生支援 |
stdClass 是 PHP 動態特性的縮影,善用它能減少樣板代碼,但切勿濫用替代正規領域模型。