The PHP stdClass() is something that isn’t well documented but i will try to shed some light into the matter. stdClass is a default PHP object which has no predefined members. The name stdClass is used internally by Zend and is reserved. So that means that you cannot define a class named stdClass in your PHP code.
It can be used to manually instantiate generic objects which you can then set member variables for, this is useful for passing objects to other functions or methods which expect to take an object as an argument. An even more likely usage is casting an array to an object which takes each value in the array and adds it as a member variable with the name based on the key in the array.
Here’s an example below that converts an array to an object below. This method is called Type Casting.
1 2 3 4 5 6 7 8 9 |
<?php $person = array ( 'firstname' => 'Richard', 'lastname' => 'Castera' ); $p = (object) $person; echo $p->firstname; // Will print 'Richard' ?> |
Here’s an example below that converts a multi-dimensional array to an object. This is accomplished through recursion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php function arrayToObject($array) { if (!is_array($array)) { return $array; } $object = new stdClass(); if (is_array($array) && count($array) > 0) { foreach ($array as $name=>$value) { $name = strtolower(trim($name)); if (!empty($name)) { $object->$name = arrayToObject($value); } } return $object; } else { return FALSE; } } ?> |
1 2 3 4 5 6 7 |
<?php $person = array ( 'first' => array('name' => 'Richard') ); $p = arrayToObject($person); ?> |
1 2 3 4 |
<?php // Now you can use $p like this: echo $p->first->name; // Will print 'Richard' ?> |
Hi Richard. This is very useful function to convert Array to stdClass object.
Please check out with:
Thanks
Great post!
Just discovered that
is faster than
I was looking for something like this today and found your blog. While I couldn’t get your solution to work (probably because I’m really tired at the moment 🙁 but it did inspire me to create my own version which I thought I would share:
Its a little more compact and easier to follow I think. You can also embellish and add in the strtolower and trim for the properties if you like.
You can also define your own class:
Then use it like this:
Hi maybe the following onliner-function is also a possible solution for some of you. It is part of a static method of a class named ‘Type’. So it can be replaced by a global method if needed:
And try to avoid the following mistake. It took me a moment to realize it when I made the mistake. An example:
Make a choice what type of object-properties you want: integer ($oTestInt) or string ($oTestString).
I found out another way. I was looking for a way to reference the array returned from a function and happened on your post. As is turns out it is impossible in PHP to do what I wanted. Well, I FOUND A WORKAROUND, using your post and users’ comments I was inspired. It’s not elegant and probably has more CPU overhead. Hopefully it helps somebody who is trying to do the same thing I was.
Here’s what I wanted to do:
Then I found your post on how to convert arrays to objects thinking that I could:
But that doesn’t work in PHP. So finally I came up with:
SUCCESS!! I just don’t know why there isn’t a function to do this already. Perhaps the powers that be will copy the part of JSON handling that is converting the data to an object and make it into a built-in function. One can only hope. Thx for the post!
Just found this very useful when using WordPress’s native database access..
returns something like
trying to mimic that result from form data was doing my head in.. so thank you 🙂
i used your code and add that to my db:
Hi great post was looking for something like this however im stuck as cannot get the recursion properly working….
if i print_r the config object i get… when not using the recursive method which fine except for the C ARRAY which is expected.
however when i use the method as recursive i get…
so i love the object after the first array and also adds some crap to the end 🙁
any help would be greatly appreciated…
What I always do to preserve multidimensionality is json_decode(json_encode());
I’d like to share my solution using json with php 5.3 up
É mais fácil assim oh…
código limpo e sem brecha pra erro..
bele?
um abraço…
Hi,
I am using this code from 2 years and this morning I found a bug 😉
If the name of the array is zero [0], array_to_object() skip that array. For example in this array:
The result after used array_to_object() is:
To fix this, replace
to
Many thanks Richard for your help with this code 😀
Rémi
Hey Richard, I really like your blog! It’s great! Also Google ads are very smoothly integrated.
I really like this … thanks
Great post Richard! I was having a problem with a class I needed to serialize to store the value but I needed dynamic variables and stdClass kept erroring out saying:
Fatal error: Cannot access empty property
It didn’t even occur that I should just create an assoc array and cast it to an object. Thanks for publishing this!
Thanks for sharing that!
Very nice function indeed,
However I’m having a problem at this moment, it seems that when I call the function to convert an multidimensional associate array, it chops off the first element in the converted stdobject
I’ll let you know what I find out.
I too was having the same problem as Chang using this code where the first element of an multidimensional associate array was being lost.
The problem is in the test “!empty($name)”. If the array uses numeric indices, index zero is considered empty.
I changed “!empty($name)” to “!is_null($name)” and conversion worked as expected.
Interesting, all the samples that I found on the web use the !empty test and would all fail to convert for zero index.
Hope this helps.
I’m trying to implement this with CJ SOAP API, but I think CJ SOAP API is more complicated, I’m still not able to convert stdClass Object to Array.
stdClass is an internal class name, not documented and so not recommended to use directly. it might even change in future php versions. instead, you should stick to converting arrays to object, or if you just need a blank object, convert a null to object.
With all due respect, many frameworks like Drupal will come to a screaming halt if using stdClass directly is disallowed so I think its safe to say that stdClass will be a usable term for the foreseeable future.
Buddy! You are best!
I waste 3 hr in looking for this.
Tnx very-very!
Hello Richard!
Just got here from Google, I am currently working on something to do with the Twitter API and that makes a array and stuff. And this just helped me to get the most recent status, I am very grateful, for this! Thank you!
Thank you, that has me very helped.
Cool, this is what i was looking for.
Man, Your the rock.
I’ve made a similar solution and also a php extension that does that:
http://freebsd.co.il/cast/
Simple and awesome . Thanks
Great. Just what I was looking for, and thanks for the sharing.
What I’m after now, is something that does the reverse, lets me now work with that object as an array.
Works great, thanks!
Nice work Richard! Was a little bit confused about stdClass. Thank you!
It works, Thank you very much, 🙂 ..
Hey Richard,
I just wanted to say thanks for the solution.
Much much much of my time was saved because of your code!
You saved my life with this! I’m newish to PHP, and the “->” operator was driving me nuts! (Try searching for “->” on Google sometime, you’ll see what I mean!)
Thanks!
Thanks for sharing! 🙂 Appreciate it much!
Nicely done, it’s useful to switch between associated arrays and stdClass in various frameworks.
Great article.