stdClass是PHP中的空类, 用于将其他类型转换为对象。它类似于Java或Python对象。 stdClass不是对象的基类。如果将对象转换为对象, 则不会对其进行修改。但是, 如果对对象类型进行了转换/类型转换, 则将创建stdClass的实例(如果它不是NULL)。如果为NULL, 则新实例将为空。
用途:
- stdClass通过调用成员直接访问成员。
- 在动态对象中很有用。
- 用于设置动态属性等。
<
?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 );
?>
【PHP中的stdClass是什么(如何使用?)】输出如下:
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)
推荐阅读
- 什么是OAuth(开放授权)(如何理解?)
- php中|和||或运算符的区别是什么()
- 什么是终端、控制台、Shell程序和内核()
- #yyds干货盘点#Embedding matrix
- Linux之iostat命令
- mysql的备份与恢复+实验
- Apache构建web主机
- SpringBoot | 4.1 SpringMVC的自动配置 #yyds干货盘点#
- 赵渝强使用二进制包部署Kubernetes集群