当前位置:Gxlcms > PHP教程 > PHP中的stdClass是什么

PHP中的stdClass是什么

时间:2021-07-01 10:21:17 帮助过:31人阅读

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

用途:

1.stdClass通过调用它们直接访问成员。

2.它在动态对象中很有用。

3.它用于设置动态属性等。

程序1:使用数组存储数据

<?php 
      
// 定义一个数组employee 
$employee_detail_array = array( 
    "name" => "John Doe", 
    "position" => "Software Engineer", 
    "address" => "53, nth street, city", 
    "status" => "best"
); 
  
// 显示内容
print_r($employee_detail_array); 
?>

输出:

Array
(
    [name] => John Doe
    [position] => Software Engineer
    [address] => 53, nth street, city
    [status] => best
)

程序2:使用stdClass而不是数组来存储员工详细信息(动态属性)

<?php 
      
// 定义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"; 
      
// 显示内容 
print_r($employee_object); 
?>

输出:

stdClass Object
(
    [name] => John Doe
    [position] => Software Engineer
    [address] => 53, nth street, city
    [status] => Best
)

注意:可以将数组类型转换为对象,将对象转换为数组。

程序3:将数组转换为对象

<?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); 
?>

输出:

Array
(
    [name] => John Doe
    [position] => Software Engineer
    [address] => 53, nth street, city
    [status] => Best
)

本篇文章就是关于PHP中stdClass的介绍,希望对需要的朋友有所帮助!

以上就是PHP中的stdClass是什么的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行