stdClass是PHP中的空类, 用于将其他类型转换为对象。它类似于Java或Python对象。 stdClass不是对象的基类。如果将对象转换为对象, 则不会对其进行修改。但是, 如果对对象类型进行了转换/类型转换, 则将创建stdClass的实例(如果它不是NULL)。如果为NULL, 则新实例将为空。
用途:
- stdClass通过调用成员直接访问成员。
- 在动态对象中很有用。
- 用于设置动态属性等。
程序1:使用数组存储数据
<?php
//Array definition of an employee
$employee_detail_array = array (
"name" => "John Doe" , "position" => "Software Engineer" , "address" => "53, nth street, city" , "status" => "best"
);
//Display the array content
print_r( $employee_detail_array );
?>
输出如下:
Array
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => best
)
程序2:使用stdClass而不是数组来存储员工详细信息(动态属性)
<?php
//Object-styled definition of an 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" ;
//Display the employee contents
print_r( $employee_object );
?>
输出如下:
stdClass Object
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => Best
)
注意:可以将数组类型转换为对象以及对象到数组。
程序3:将数组转换为对象
<?php
//Aarray definition of an employee
$employee_detail_array = array (
"name" => "John Doe" , "position" => "Software Engineer" , "address" => "53, nth street, city" , "status" => "best"
);
//type casting from array to object
$employee = (object) $employee_detail_array ;
print_r( $employee );
?>
输出如下:
stdClass Object
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => best
)
计划4:将对象属性转换为数组
<?php
//Object-styled definition of an 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" ;
//The object is converted into array
//using type casting
$employee_array = ( array ) $employee_object ;
//Display the result in array
print_r( $employee_array );
?>
输出如下:
Array
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => Best
)
来源:
https://www.srcmini02.com/69574.html