stdClass是PHP中的空類,用於將其他類型轉換為物件。它類似於Java或Python物件。 stdClass不是物件的基底類別。如果將對象轉換為對象,則不會對其進行修改。但是,如果轉換/類型化物件類型,則建立stdClass的實例,如果它不是NULL。如果為NULL,則新實例將為空。
用途:
1.stdClass透過呼叫它們直接存取成員。
2.它在動態物件中很有用。
3.它用於設定動態屬性等。
程式1:使用陣列儲存資料
<?php // 定义一个数组employee $employee_detail_array = array( "name" => "John Doe", "position" => "Software Engineer", "address" => "53, nth street, city", "status" => "best" ); // 显示内容 print_r($employee_detail_array); ?>
輸出:
Array ( [name] => John Doe [position] => Software Engineer [address] => 53, nth street, city [status] => best )
程式2:使用stdClass而不是陣列來儲存員工詳細訊息(動態屬性)
<?php // 定义employee对象样式 $employee_object = new stdClass; $employee_object->name = "John Doe"; $employee_object->position = "Software Engineer"; $employee_object->address = "53, nth street, city"; $employee_object->status = "Best"; // 显示内容 print_r($employee_object); ?>
輸出:
stdClass Object ( [name] => John Doe [position] => Software Engineer [address] => 53, nth street, city [status] => Best )
注意:可以將陣列類型轉換為對象,將物件轉換為陣列。
程式3:將陣列轉換為物件
<?php // $employee_detail_array = array( "name" => "John Doe", "position" => "Software Engineer", "address" => "53, nth street, city", "status" => "best" ); // 从数组到对象的类型转换 $employee = (object) $employee_detail_array; print_r($employee); ?>
輸出:
Array ( [name] => John Doe [position] => Software Engineer [address] => 53, nth street, city [status] => Best )
本篇文章就是關於PHP中stdClass的介紹,希望對需要的朋友有幫助!
以上是PHP中的stdClass是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!