3 ms·
I always wondered why you want to deserialize JSON as ab object tree instead of associative array. Just because the syntax is nicer? I mean, your ide still can'
by iforgotpassword 5y ago
I always wondered why you want to deserialize JSON as ab object tree instead of associative array. Just because the syntax is nicer? I mean, your ide still can't autocomplete the fields for you since it's just a stdclass and it doesn't know anything about the JSON structure right?
Also, probably not relevant in practice, but one of those two is probably faster?
- toast0 5y agoYou can get an associative array with one more parameter, so that's what I do. Array access is nicer than object access to me, but maybe that's just me.
- tored 5y agoOne important difference is how you will pass the decoded JSON data afterwards within your application, objects are passed as reference and arrays are passed as copy on write, thus if you intent to modify it it can be easer with an object. Another is if you going to merge JSON data and send it further then an object can be easier because that is how the rest of the world views it. However there many more array functions in the standard library than object functions. I think it is generally easier to annotate arrays vs objects with phpdoc. If this blog post is still true today when it was written (2018 PHP 7.2), then arrays are better for performance vs stdClass, but a real class is better than both, but sadly you can't JSON decode into a class directly. https://steemit.com/php/@crell/php-use-associative-arrays-basically-never https://steemit.com/php/@crell/php-use-associative-arrays-ba...
- withinboredom 5y agoArrays probably offer a better memory management experience. It’s probably way easier to accidentally close over the json object in a closure than an array. But if you want “spooky action at a distance”, objects are the way to go.
- lambic 5y agoAs far as speed is concerned (and yes this is a generalization): defined object > dynamic object > array But it's very much a micro-optimization.
- duskwuff 5y ago> I always wondered why you want to deserialize JSON as ab object tree instead of associative array. To prevent [] and {} from both being deserialized to an empty array.
- falsenapkin 5y agoThis is the most convincing answer to me. I learned this the hard way recently.