Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return object instead of array?

Tags:

php

I do a lot of work in WordPress, and I've noticed that far more functions return objects than arrays. Database results are returned as objects unless you specifically ask for an array. Errors are returned as objects. Outside of WordPress, most APIs give you an object instead of an array.

My question is, why do they use objects instead of arrays? For the most part it doesn't matter too much, but in some cases I find objects harder to not only process but to wrap my head around. Is there a performance reason for using an object?

I'm a self-taught PHP programmer. I've got a liberal arts degree. So forgive me if I'm missing a fundamental aspect of computer science. ;)

like image 767
Dennis Avatar asked Jul 15 '11 17:07

Dennis


People also ask

Why is it better to use objects instead of arrays?

Both objects and arrays are considered “special” in JavaScript. Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value). Arrays are a special type of variable that is also mutable and can also be used to store a list of values.

Why is object object being returned?

[object Object] is a string version of an object instance. This value is returned by a JavaScript program if you try to print out an object without first formatting the object as a string.

What does returning an object mean?

Return by value means the the value in the obj reference is returned, if obj points to some object,other reference which collects a return value from this returning method will also point to the same object as which obj is pointing to.

Why Typeof array is object in JavaScript?

Apparently there seems to be something wrong because the array is recognized as an object and seems to be no real difference between object and array. This because in javascript all derived data type is always a type object. Included functions and array.


1 Answers

These are the reasons why I prefer objects in general:

  • Objects not only contain data but also functionality.
  • Objects have (in most cases) a predefined structure. This is very useful for API design. Furthermore, you can set properties as public, protected, or private.
  • objects better fit object oriented development.
  • In most IDE's auto-completion only works for objects.

Here is something to read:

  • Object Vs. Array in PHP
  • PHP stdClass: Storing Data in an Object Instead of an Array
  • When should I use stdClass and when should I use an array in php5 oo code
  • PHP Objects vs Arrays
  • Mysql results in PHP - arrays or objects?
  • PHP objects vs arrays performance myth
  • A Set of Objects in PHP: Arrays vs. SplObjectStorage
  • Better Object-Oriented Arrays
like image 55
Sascha Galley Avatar answered Sep 29 '22 07:09

Sascha Galley