📜  php stdclass - PHP (1)

📅  最后修改于: 2023-12-03 15:03:35.851000             🧑  作者: Mango

PHP stdClass

The stdClass is a default PHP class that is used to create objects. It is an empty class that can be used to hold arbitrary data. In other words, the stdClass serves as a generic container for any data type.

Creating an Instance of stdClass

To create an instance of the stdClass class, you simply instantiate it.

$myObject = new stdClass();

This creates a new instance of the stdClass object named $myObject.

Adding Properties to stdClass Object

To add properties to a stdClass object, you can use the -> operator.

$myObject->name = 'John';
$myObject->age = 30;
$myObject->city = 'New York';

Note that we are using the object operator -> to add properties to the object.

Accessing Properties of stdClass Object

To access the properties of a stdClass object, you can also use the -> operator.

echo $myObject->name; // Outputs: John
echo $myObject->age; // Outputs: 30
echo $myObject->city; // Outputs: New York
Converting stdClass Objects to Arrays

Sometimes, you may need to convert a stdClass object to an array. This can be done using the get_object_vars() function.

$myArray = get_object_vars($myObject);

// Outputs: 
// Array (
//     [name] => John
//     [age] => 30
//     [city] => New York
// )
Conclusion

The stdClass class is a simple and useful way to create a generic container for any data type in PHP. It is easy to use and convenient for holding an arbitrary amount of data.