PHP中的stdClass是什么?本篇文章就来带大家认识一下PHP中的stdClass,介绍它的用途和使用方法,希望对大家有所帮助。
stdClass是什么?有什么用?
stdClass是PHP中的类原型、空类,它是最简单的对象,用于将其他类型转换为对象;它类似于Java或Python对象。
stdClass不是对象的基类。如果将对象转换为对象,则不会对其进行修改。但是,在不是NULL的情况下,如果转换对象的类型,则创建stdClass的实例;如果为NULL,则新实例将为空。
用途:
1、stdClass通过调用它们直接访问成员。
2、它在动态对象中很有用。
3、它用于设置动态属性等。
stdClass的使用示例
下面我们通过示例来简单介绍stdClass的使用。
示例1:对比使用数组和stdClass存储数据
使用数组存储数据
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php header( "content-type:text/html;charset=utf-8" ); // 定义一个学生数组 $student_detail_array = array ( "student_id" => "18201401" , "name" => "李华" , "age" => "20" , "college" => "计算机科学" ); // 显示数组内容 var_dump( $student_detail_array ); ?> |
输出:
使用stdClass而不是数组来存储学生信息(动态属性)
1 2 3 4 5 6 7 8 9 10 11 12 | <?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 = "计算机科学" ; // 显示学生对象的内容 var_dump( $student_object ); ?> |
输出:
注意:可以将数组类型转换为对象,将对象转换为数组。
示例2:将数组转换为对象
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php header( "content-type:text/html;charset=utf-8" ); // 定义一个学生数组 $student_detail_array = array ( "student_id" => "18201401" , "name" => "李华" , "age" => "20" , "college" => "计算机科学" ); $employee = (object) $student_detail_array ; // 显示数组内容 var_dump( $employee ); ?> |
输出:
示例3:将对象属性转换为数组
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?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 ; // 显示学生对象的内容 var_dump( $student_array ); ?> |
输出:
以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注php中文网相关教程栏目!!!
以上就是PHP中的stdClass是什么?如何使用?(代码示例)的详细内容,更多请关注php中文网其它相关文章!