January 23, 2023 | Posted in PHP
What is stdClass?
stdClass is a built-in class in PHP that can be used to create objects without defining an explicit class. It can be used as a generic container for properties and methods, and is often used when the structure of an object is not known until runtime.
For example, it is commonly used when working with JSON data, as the data structure may not be known ahead of time. You can create an instance of stdClass using the new keyword and add properties and methods to it like any other object.
stdClass can be used in a variety of situations where the structure of an object is not known until runtime. Some common use cases include:
Here is an example of using stdClass
to create an object that holds data from a JSON string:
<?php
$json = '{"name": "John", "age": 30, "city": "New York"}';
// Decode the JSON string into an object
$data = json_decode($json);
// The json_decode function returns an object of type stdClass by default
// You can access the properties like you would with any other object
echo $data->name; // Outputs "John"
echo $data->age; // Outputs 30
echo $data->city; // Outputs "New York"
Here is an example of using stdClass
to create an object on the fly
<?php
$obj = new stdClass();
$obj->name = "John";
$obj->age = 30;
$obj->city = "New York";
echo $obj->name; // Outputs "John"
echo $obj->age; // Outputs 30
echo $obj->city; // Outputs "New York"
In both examples above, the stdClass
object is created and properties are added to it just like any other object.