stdClass是什么?有什么用?
stdClass是PHP中的類原型、空類,它是最簡單的對象,用于將其他類型轉換為對象;它類似于Java或Python對象。
stdClass不是對象的基類。如果將對象轉換為對象,則不會對其進行修改。但是,在不是NULL的情況下,如果轉換對象的類型,則創(chuàng)建stdClass的實例;如果為NULL,則新實例將為空。
用途:
1、stdClass通過調用它們直接訪問成員。
2、它在動態(tài)對象中很有用。
3、它用于設置動態(tài)屬性等。
stdClass的使用示例
下面我們通過示例來簡單介紹stdClass的使用。
示例1:對比使用數(shù)組和stdClass存儲數(shù)據(jù)
使用數(shù)組存儲數(shù)據(jù)
?php header( content-type:text/html;charset=utf-8 // 定義一個學生數(shù)組$student_detail_array = array( student_id = 18201401 , name = 李華 , age = 20 , college = 計算機科學 // 顯示數(shù)組內(nèi)容var_dump($student_detail_array); ?
輸出:
使用stdClass而不是數(shù)組來存儲學生信息(動態(tài)屬性)
?php header( content-type:text/html;charset=utf-8 // 定義一個學生對象$student_object = new stdClass; $student_object- student_id = 18201401 $student_object- name = 李華 $student_object- age = 20; $student_object- college = 計算機科學 // 顯示學生對象的內(nèi)容var_dump($student_object); ?
輸出:
注意:可以將數(shù)組類型轉換為對象,將對象轉換為數(shù)組。
示例2:將數(shù)組轉換為對象
?php header( content-type:text/html;charset=utf-8 // 定義一個學生數(shù)組$student_detail_array = array( student_id = 18201401 , name = 李華 , age = 20 , college = 計算機科學 $employee = (object) $student_detail_array; // 顯示數(shù)組內(nèi)容 var_dump($employee); ?
輸出:
示例3:將對象屬性轉換為數(shù)組
?php header( content-type:text/html;charset=utf-8 // 定義一個學生對象$student_object = new stdClass; $student_object- student_id = 18201401 $student_object- name = 李華 $student_object- age = 20; $student_object- college = 計算機科學 $student_array = (array) $student_object; // 顯示學生對象的內(nèi)容var_dump($student_array); ?
輸出:
以上就是本篇文章的全部內(nèi)容,希望能對大家的學習有所幫助。更多精彩內(nèi)容大家可以關注php 相關教程欄目!!!
以上就是PHP中的stdClass是什么?如何使用?(代碼示例)的詳細內(nèi)容,PHP教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。
新聞熱點
疑難解答