Ever encountered scenarios in PHP where creating objects dynamically without adhering to a predefined class structure was the need of the hour? Enter stdClass – PHP's versatile, blank canvas for on-the-fly object creation!
Here's how stdClass comes to the rescue:
What is stdClass?
stdClass is a handy feature to create a regular class in PHP. It is a predefined 'empty' class used as a utility class to cast objects of other types. It has no parents, properties, or methods. It also does not support magic methods and does not implement any interfaces.[Source educative]
1️⃣ Dynamic Object Creation:
With stdClass, you can fashion objects without the constraints of a defined class, perfect for holding arbitrary data.
php
$person = new stdClass();
$person->name = 'John Doe';
$person->age = 30;
$person->email = 'john@example.com';
2️⃣ JSON Handling:
When dealing with dynamic JSON structures, decoding JSON strings into PHP objects using json_decode with stdClass proves incredibly handy.
php
$jsonString = '{"name":"Alice","age":25,"email":"alice@example.com"}';
$personObj = json_decode($jsonString);
3️⃣ Dynamic Data Interaction:
Working with fluctuating data from external sources like APIs? stdClass allows seamless property assignment for versatile data handling.
php
$apiData = fetchDataFromApi();
$apiObject = new stdClass();
foreach ($apiData as $key => $value) {
$apiObject->$key = $value;
}
4️⃣ Dynamic Object Returns:
Functions or methods can effortlessly return dynamic objects using stdClass.
php
function createDynamicObject() {
$dynamicObj = new stdClass();
$dynamicObj->property1 = 'value1';
$dynamicObj->property2 = 'value2';
return $dynamicObj;
}
$result = createDynamicObject();
While stdClass offers flexibility in ad-hoc object creation, it lacks the robustness of class-based OOP. It's ideal for immediate use cases where object structure and behavior remain fluid.
Harness the simplicity and versatility of stdClass for your dynamic PHP needs!
Top comments (10)
Hi.
To increase readability you should surround code snippets with triple backticks (add
php
after the opening backticks for syntax coloring).Thank you @joolsmcfly for your great suggestion. I am really happy to join here. Keep supporting me.
I would even be more happy if you just give me a screenshot for syntax coloring.
which renders as
Awesome.
Thank you so much.
If you could add an example on how to convert a stdClass to a defined class it would be even better.
Now rest of your code knows it's dealing with an array of User objects and you've unlocked type hinting, autocompletion etc.
Thank you for explaining it further. Love it.
Hello. Not sure it's a good idea to use dynamic properties (see php.watch/versions/8.2/dynamic-pro...). It's perhaps still working for stdClass (not tried) but, yes, you should probably avoid this use case for ever.
Thank you.
I will look into this.
Alternatively, instead of
you could just write
which is also a way of creating a stdClass() instance.