What is stdClass in PHP?

Discover the stdClass object in PHP with our comprehensive guide. Learn how to use this built-in PHP class to create simple and dynamic objects on-the-fly, without having to define a new class. Improve your PHP programming skills today!

As a developer, when you code web applications and especially large scaled ones, you are going to use the notion of the object at some point. All those conventional data structures may not cut it depending the use case and the issue that you are trying to solve. That is why at some point you may need to create your own data structure with the properties of your choice that are going to match your needs perfectly. You can achieve such thing using an object of the stdClass. Objects can be very versatile when you want to change them. You should read about it here.

An stdClass is a class that enables you to create your own object map that you dynamically allocate with the values of your choice without defining the class as is within the file or any file since it’s built in PHP.

How to use an stdClass

To create an stdClass object you use the new keyword as you would do with an object of any class and the name of the class (stdClass in this case). Observe.

$item = new stdClass();
$item->price = 343.34;
$item->desc = 'This is a test item.';
echo '$' . $item->price; // prints: $343.34

StdClass objects are mainly used with casting or when you want to format the data fetched from some kind of database medium. Sometimes the data you get isn’t the data you want and you may need to convert the stdClass back to an array in order to fulfill some kind of requirement.

echo '<pre>';
$s = new stdClass();
$s->id = 23;

$data = array(); 
foreach($s as $k=>$v){
    $data[$k] = $v;
}
print_r($data);

It’s a good practice to have a helper function that will convert an stdClass object into an array so you can use it whenever you want, keeping your code nice and concise. Avoid using json_encode and json_decode functions for the conversion. Those two functions in combination will cause performance problems depending the size of the dataset that you’re trying to modify.

function std_to_array($std) {
    $ret = array();
    foreach($std as $k=>$v) {
        $ret[$k] = $v;
    }
    return $ret;
}

$s = new stdClass();
$s->id = 23;

print_r(std_to_array($s));

For a quick and dirty solution and without any possibility of additional customization, you can use the array casting directly to the stdClass object to convert it into an array.

$s = new stdClass();
$s->id = 23;
$s = (array) $s;
print_r($s);