stdClass是什么?有什么用?
stdClass是PHP中的类原型、空类,它是最简朴的对象,用于将其他范例转换为对象;它类似于Java或Python对象。
stdClass不是对象的基类。假如将对象转换为对象,则不会对其举行修正。然则,在不是NULL的情况下,假如转换对象的范例,则建立stdClass的实例;假如为NULL,则新实例将为空。
用处:
1、stdClass经由过程挪用它们直接接见成员。
2、它在动态对象中很有效。
3、它用于设置动态属性等。
stdClass的运用示例
下面我们经由过程示例来简朴引见stdClass的运用。
示例1:对照运用数组和stdClass存储数据
运用数组存储数据
<?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而不是数组来存储门生信息(动态属性)
<?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:将数组转换为对象
<?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:将对象属性转换为数组
<?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); ?>
输出:
以上就是本篇文章的全部内容,愿望能对人人的进修有所协助。更多精彩内容人人能够关注ki4网相干教程栏目!!!
以上就是PHP中的stdClass是什么?怎样运用?(代码示例)的细致内容,更多请关注ki4网别的相干文章!