Why return an object instead of an array?

I work a lot in WordPress, and I noticed that a lot more functions return objects than arrays. Database results are returned as objects, unless you specifically request the array. Errors are returned as objects. Outside of WordPress, most of the APIs provide you with an object instead of an array.

My question is: why do they use objects instead of arrays? For the most part, this does not matter much, but in some cases I find it more difficult to not only process, but also wrap my head. Is there a reason to use to use the object?

I am a PHP programmer. I have a degree in liberal art. So forgive me if I missed the fundamental aspect of computer science.;)

+80
php
Jul 15 '11 at 17:32
source share
15 answers

This is 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 designing an API. In addition, you can set properties as public, protected, or private.
  • objects are better suited for object-oriented development.
  • In most autocomplete IDEs only work for objects.

Here's what you can read:

+58
Jul 15 '11 at 17:50
source share

This is probably not something you will deeply understand until you work on a major software project for several years. Many new specialists in the field of computer science will give you an answer with all the right words (encapsulation, functionality with data and maintainability), but few will understand why all this is good.

Let's skip a few examples.

  • If the arrays were returned, then either all values ​​must be calculated in front, or many small values ​​need to be returned, from which you can build more complex values.

Think of an API method that returns a list of WordPress posts. These posts have authors, authors have names, an email address, perhaps even profiles with their biographies.

If you return all messages in the array, you will either have to limit yourself to returning an array of mail identifiers:

[233, 41, 204, 111]

or returns a massive array that looks something like this:

 [ title: 'somePost', body: 'blah blah', 'author': ['name': 'billy', 'email': 'bill@bill.com', 'profile': ['interests': ['interest1', 'interest2', ...], 'bio': 'info...']] ] [id: '2', .....]] 

The first case of returning the list of identifiers is not very useful for you, because then you need to make an API call for each identifier in order to get some information about this message.

The second case will provide more information than you need 90% of the time, and will do more work (especially if any of these fields is very difficult to build).

An object, on the other hand, can provide you with access to all the information you need, but so far it has not actually pulled this information. The determination of field values ​​can be done lazily (i.e. when the value is necessary, and not in advance) when using the object.

  • Arrays provide more data and capabilities than anticipated.

Let's go back to the example of a massive array that is returned. Now someone can probably create an application that iterates over each value inside the post array and prints it. If the API is updated to add only one additional element to this post-array, then the application code is about to break, as it will print a new field, which probably shouldn't. If the order of the elements in the message array returned by the API changes, this will also violate the application code. Therefore, returning an array creates all kinds of dependencies that the object would not create.

  • Functionality

An object can store information inside it, which allows it to provide you with useful functions. For example, the post object may be smart enough to return previous or next posts. The array could not do this for you.

  • Flexibility

All the advantages of the above objects help create a more flexible system.

+22
Jul 15 '11 at 19:09
source share

My question is: why do they use objects instead of arrays?

There are probably two reasons:

  • WordPress is pretty old
  • arrays are faster and in most cases take up less memory.
  • easier to serialize

Is there a reason to use to use the object?

No. But there are many other good reasons, for example:

  • you can store logic in objects (methods, closure, etc.).
  • you can force the structure of an object to use an interface
  • best autocomplete in the IDE
  • you do not receive notifications for undefined keys
  • in the end you can easily convert any object to an array

OOP ! = AOP :)

(For example, in Ruby, everything is an object. PHP used to be a procedure / script language.)

+10
Jul 15 '11 at 18:50
source share

WordPress (and a significant number of other PHP applications) use objects, not arrays, for conceptual rather than technical reasons.

An object (even if only an instance of stdClass) is a representation of one thing. In WordPress, it can be a post, comment, or user. An array, on the other hand, is a collection of things. (For example, a list of messages.)

Historically, PHP did not have much support for objects, so arrays became quite powerful early on. (For example, the ability to have arbitrary keys, rather than just indexing with a zero mark.) Thanks to the object support available in PHP 5, developers now have a choice between using arrays or objects as key stores. Personally, I prefer the WordPress approach, because I like the syntactic difference between “entities” and “collections” that provide objects and arrays.

+7
Jul 15 '11 at 19:48
source share

My question is: why do they (Wordpress) use objects instead of arrays?

This is a really good question and not easy to answer. I can only assume that Wordpress typically uses the stdClass object because they use the database class, which by default returns records as the stdClass object. They are used to it (8 years or more) and what it is. I do not think that there is much more thought behind a simple fact.

syntactic sugar for associative arrays - Zeev Suraski about a standard object with PHP 3

  • stdClass objects are no better than arrays. They are almost the same. That, for some historical reasons, for both the language and the stdClass objects stdClass really limited and in fact are just value objects in a very simple sense.
  • stdClass objects store values ​​for its members, like an array, for each record. What is it.
  • Only PHP freaks can create stdClass objects with private members. Not much good — if any — does it.
  • stdClass objects do not have methods / functions. So do not use this in Wordpress.
  • Compared to array there is a much less useful function for processing list or semi-structured data.

However, if you are used to arrays, just click:

 $array = (array) $object; 

And you can access data previously an object as an array. Or do you like it the other way around:

 $object = (object) $array; 

Which will only result in invalid member names, such as numbers. So take a little care. But I think you get the big picture: there is not much difference when it comes to arrays and stdClass objects.

Connected:

+5
Jul 15 '11 at 18:08
source share

Objects are much more powerful than arrays. Each object as an instance of a class can have attached functions. If you have data that needs processing, you need a function that performs the processing. With an array, you have to call this function on this array and, therefore, associate the logic with the data. This association has already been made with the object, and you no longer need to take care of it.

You should also consider the principle of secrecy of OO information. Not everything that is returned or received in the database must be directly accessible.

+4
Jul 15 '11 at 17:37
source share
  • The code looks cooler this way
  • Objects follow the link
  • Objects are stronger and then arrays, so lees pron to errors (or gives you a meaningful error message when trying to use a nonexistent element)
  • All IDEs today have automatic completion, so when working with certain objects, the ID environment does a lot for you and speeds up the work.
  • It is easy to encapsulate logical and data in the same field as with arrays, you store data in an array, and then use a set of different functions to process it.
  • Inheritance. If you had a similar array with almost, but not similar functionality, you would have to duplicate more code if you want to do this with objects

Perhaps another reason I thought about

+4
Jul 15 '11 at 17:40
source share

There are several reasons to return objects:

  • Writing $myObject->property requires less "service" characters than $myArray['element']

  • An object can return data and functionality; arrays can only contain data.

  • Enable the chain: $myobject->getData()->parseData()->toXML();

  • Simple coding: autocomplete IDE can provide method and property hints for an object.

In terms of performance, arrays are often faster than objects. In addition to performance, there are several reasons to use arrays:

  • The functionality provided by the _ * () array of family functions can reduce the amount of coding needed in some cases.

  • Operations such as count () and foreach () can be performed on arrays. Objects do not offer this (unless they implement Iterator or Countable ).

+3
Jul 15 2018-11-17T00:
source share

This is generally not related to performance considerations. As a rule, objects cost more than arrays.

For many APIs, this is probably related to objects that provide functions other than the storage engine. Otherwise, it is a matter of preference, and in fact there is no use for returning an object to an array.

+2
Jul 15 2018-11-17T00:
source share

An array is just an index of values. While the object contains methods that can generate a result for you. Of course, sometimes you can directly access the values ​​of objects, but the “right way to do this” is to access the methods of the objects (a function that acts on the values ​​of this object).

 $obj = new MyObject; $obj->getName(); // this calls a method (function), so it can decide what to return based on conditions or other criteria $array['name']; // this is just the string "name". there is no logic to it. 

Sometimes you directly access object variables, this is usually disapproving, but this happens quite often.

 $obj->name; // accessing the string "name" ... not really different from an array in this case. 

However, note that the MyObject class does not have a variable named 'name', but instead has a variable first_name and last_name.

 $obj->getName(); // this would return first_name and last_name joined. $obj->name; // would fail... $obj->first_name; $obj->last_name; // would be accessing the variables of that object directly. 

This is a very simple example, but you can see where this is happening. The class provides a set of variables and functions that can work with these variables, all within an autonomous logical object. An instance of this object is called an object, and it introduces logical and dynamic results that the array simply does not have.

+2
Jul 15 2018-11-17T00:
source share

In most cases, objects are just as fast, if not faster than arrays, there is no noticeable difference in PHP. the main reason is because objects are more powerful than arrays. Object-oriented software allows you to create objects and store not only data, but also functionality in them, for example, in PHP. The MySQLi class allows you to have a database object that you can manipulate using a variety of built-in functions, rather than a procedural approach.

So the main reason is that OOP is a great paradigm. I wrote an article on why using OOP is a good idea and explains the concept, you can see here: http://tomsbigbox.com/an-introduction-to-oop/

As a secondary plus, you also enter less data to get data from the object - $ test-> data is better than $ test ['data'].

+1
Jul 15 2018-11-17T00:
source share

I am not familiar with the press. Many answers here show that the power of objects has the ability to contain functional code. When returning an object from a function / API call, it should not contain utility functions. Just properties.

The strength of returned objects is that everything behind the API can change without breaking your code.

Example. You get an array of data with key / value pairs representing the database column. If the database column is renamed, your code will break.

+1
Jul 16 '11 at 3:22
source share

Im running the following test in php 5.3.10 (windows):

 for ($i = 0; $i < 1000000; $i++) { $x = array(); $x['a'] = 'a'; $x['b'] = 'b'; } 

and

 for ($i = 0; $i < 1000000; $i++) { $x = new stdClass; $x->a = 'a'; $x->b = 'b'; } 

Copied from http://atomized.org/2009/02/really-damn-slow-a-look-at-php-objects/comment-page-1/#comment-186961

Function call for 10 simultaneous users and 10 times (to get the average value), then

  • Arrays: 100%
  • Object: 214% - 216% (2 times slower).

AKA, Object is still very slow. OOP maintains the order of things, but should be used with caution.

What does Wordpress use ?. Both solutions use objects, arrays and objects and arrays, the wpdb class uses a later one (and this is the heart of Wordpress).

+1
Mar 17 '12 at 18:16
source share

This follows the principle of boxing and unpacking OOP. Although languages ​​such as Java and C # support this natively, PHP does not. However, this can be achieved, to some extent, in PHP, simply not eloquently, since the language itself has no constructs to support it. Having field types in PHP can help in the chain, preserving everything object-oriented and letting you type in the method signatures. The disadvantage is the overhead and the fact that you now have an extra check using the construct. Having a type system is also a plus when using development tools that have intellisense or code, such as PDT. Instead of using the google / bing / yahoo method for this method, it exists on the object, and you can use this tool to provide dropout.

0
Jul 16 '11 at 5:24 a.m.
source share

Although points made about objects more than just data are valid because they are usually data and behavior, there is at least one pattern mentioned in Martin Fowler's “Application Architecture Patterns” that applies to this type of cenario, in which you transfer data from one system (application for API) and another (your application).

Own Data Transfer Object - an object that transfers data between processes in order to reduce the number of method calls.

So, if the question is whether the APIs should return a DTO or an array, I would say that if the performance cost is negligible, then you should choose an option that is more maintainable, which I would say is the DTO option .. But of course, you should also consider the skills and culture of the team that develops your system and language or IDE support for each option.

0
Mar 03 '15 at 11:46
source share



All Articles