stdClass 是 PHP 內建的預定義類別,本質上是一個空白的基類,不包含任何屬性與方法。它常被用作「資料傳遞物件」(DTO),讓開發者無需自行定義類別即可將陣列轉為物件,方便屬性式存取。
$andy = array(); $andy = (object)$andy; // 強制轉型 $andy->a = 1; $andy->b = 2; $andy->c = 3;
$a = new stdClass(); $a->id = '11'; $a->username = 'me'; print_r($a); // 輸出:stdClass Object ( [id] => 11 [username] => me )
與陣列 $arr['key'] 不同,物件使用箭頭運算子:
$weather->getWeatherbyCityNameResult->string[0] // 取得「四川」
$a = array(1=>2, 2=>3); $a = (object)$a; $a->id = '11'; $a->username = 'me'; print_r($a); // 輸出:stdClass Object ( [1] => 2 [2] => 3 [id] => 11 [username] => me )
$a = array(1=>2, 2=>3); $a = (object)$a; $a = new stdClass(); // 重新實例化,舊資料遺失 $a->id = '11'; $a->username = 'me'; print_r($a); // 輸出:stdClass Object ( [id] => 11 [username] => me )
global/static 使用 new stdClass 時,避免使用引用賦值(&new stdClass 會失效),直接用 new stdClass() 即可json_decode($json) 等同 json_decode($json, false)stdClass 基礎模型)善用 stdClass 可減少樣板代碼,但在大型專案中建議配合介面或資料傳輸物件(DTO)模式使用,提升代碼可維護性。