📜  PHP的stdClass 是什么?

📅  最后修改于: 2022-05-13 02:24:09.525000             🧑  作者: Mango

PHP的stdClass 是什么?

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

用途:

  • stdClass 通过调用成员直接访问成员。
  • 它在动态对象中很有用。
  • 它用于设置动态属性等。

方案一:使用数组存储数据

 "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 而不是数组来存储员工详细信息(动态属性)



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:将数组转换为对象

 "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);
?>
输出:
stdClass Object
(
    [name] => John Doe
    [position] => Software Engineer
    [address] => 53, nth street, city
    [status] => best
)

程序 4:将对象属性转换为数组

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
)

PHP是一种专门为 Web 开发设计的服务器端脚本语言。您可以按照此PHP教程和PHP示例从头开始学习PHP 。