首页  >  文章  >  后端开发  >  PHP中的stdClass是什么

PHP中的stdClass是什么

藏色散人
藏色散人原创
2019-01-28 10:48:222908浏览

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

PHP中的stdClass是什么

用途:

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是什么的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn