Home  >  Article  >  Backend Development  >  What is stdClass in PHP

What is stdClass in PHP

藏色散人
藏色散人Original
2019-01-28 10:48:222965browse

stdClass is an empty class in PHP used to convert other types to objects. It is similar to a Java or Python object. stdClass is not the base class of objects. If you convert an object to an object, it will not be modified. However, if you convert/type the object type, an instance of stdClass is created if it is not NULL. If NULL, the new instance will be empty.

What is stdClass in PHP

Purpose:

1.stdClass directly access members by calling them.

2. It is useful in dynamic objects.

3. It is used to set dynamic properties, etc.

Program 1: Use array to store data

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

Output:

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

Program 2: Use stdClass instead of array to store employee details Information (Dynamic Properties)

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

Output:

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

Note: You can convert array types to objects and objects to arrays.

Program 3: Convert array to object

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

Output:

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

This article is an introduction to stdClass in PHP, I hope it will help you if you need Friends help!

The above is the detailed content of What is stdClass in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn