r/PHPhelp • • May 31 '19

What are the differences between using object (`stdClass`) and associative array?

After reading this: https://www.webmaster-source.com/2009/08/20/php-stdclass-storing-data-object-instead-array/.

I was wondering what are the differences between using object (stdClass) and associative array? Are there any performance benefit of each others? When should I use array and when should create stdClass instead?

7 Upvotes

5 comments sorted by

3

u/holyshock May 31 '19 edited May 31 '19

These other answers are a bit misleading. There's a lot of reasons to use an Object over an Array. Objects are a bit slower, like /u/AegirLeet said, however it's a minor performance boost in the same way that using single quotes are faster than double quotes (i.e., no one cares). I'm not suggesting you blanket use StdClass over arrays, but instead build your own Class that adds value for your context.

Some reading as to why Objects > Arrays:

https://dev.to/aleksikauppila/dont-return-associative-arrays-28il

2

u/akas84 May 31 '19

Exactly. The thing would be: never use stdClass. Use meaningful classes that add logic to your application

0

u/the_alias_of_andrea May 31 '19

But OP isn't asking about objects in general, they're asking about stdClass.

1

u/AegirLeet May 31 '19

You should almost never use a plain stdClass. Arrays are easier to work with and offer better performance (although this won't matter much unless you're instantiating hundreds of thousands of arrays/objects).

0

u/the_alias_of_andrea May 31 '19

->foo is shorter than ['foo']. That's all that stdClass has in its favour really.