stdClass是PHP中的空类,用于将其他类型转换为对象。它类似于Java或Python对象。stdClass不是对象的基类。如果将对象转换为对象,则不会对其进行修改。但是,如果转换/类型化对象类型,则创建stdClass的实例,如果它不是NULL。如果为NULL,则新实例将为空。

用途:
1.stdClass通过调用它们直接访问成员。
2.它在动态对象中很有用。
3.它用于设置动态属性等。
程序1:使用数组存储数据
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php
$employee_detail_array = array (
"name" => "John Doe" ,
"position" => "Software Engineer" ,
"address" => "53, nth street, city" ,
"status" => "best"
);
print_r( $employee_detail_array );
?>
|
Salin selepas log masuk
输出:
1 2 3 4 5 6 7 | Array
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => best
)
|
Salin selepas log masuk
程序2:使用stdClass而不是数组来存储员工详细信息(动态属性)
1 2 3 4 5 6 7 8 9 10 11 12 | <?php
$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" ;
print_r( $employee_object );
?>
|
Salin selepas log masuk
输出:
1 2 3 4 5 6 7 | stdClass Object
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => Best
)
|
Salin selepas log masuk
注意:可以将数组类型转换为对象,将对象转换为数组。
程序3:将数组转换为对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php
$employee_detail_array = array (
"name" => "John Doe" ,
"position" => "Software Engineer" ,
"address" => "53, nth street, city" ,
"status" => "best"
);
$employee = (object) $employee_detail_array ;
print_r( $employee );
?>
|
Salin selepas log masuk
输出:
1 2 3 4 5 6 7 | Array
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => Best
)
|
Salin selepas log masuk
本篇文章就是关于PHP中stdClass的介绍,希望对需要的朋友有所帮助!
Atas ialah kandungan terperinci PHP中的stdClass是什么. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!