Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value objects vs associative arrays in PHP

(This question uses PHP as context but isn't restricted to PHP only. e.g. Any language with built in hash is also relevant)

Let's look at this example (PHP):

function makeAFredUsingAssoc() {     return array(         'id'=>1337,         'height'=>137,         'name'=>"Green Fred"); } 

Versus:

class Fred {     public $id;     public $height;     public $name;      public function __construct($id, $height, $name)     {         $this->id = $id;         $this->height = $height;         $this->name = $name;     } }  function makeAFredUsingValueObject() {     return new Fred(1337, 137, "Green Fred"); } 

Method #1 is of course terser, however it may easily lead to error such as

$myFred = makeAFredUsingAssoc(); return $myFred['naem']; // notice teh typo here 

Of course, one might argue that $myFred->naem will equally lead to error, which is true. However having a formal class just feels more rigid to me, but I can't really justify it.

What would be the pros/cons to using each approach and when should people use which approach?

like image 530
kizzx2 Avatar asked Jan 13 '10 13:01

kizzx2


People also ask

What is the difference between associative array and object in PHP?

An object is an instance of a class. It is simply a specimen of a class and has memory allocated. Array is the data structure that stores one or more similar type of values in a single name but associative array is different from a simple PHP array. An array which contains string index is called associative array.

What is the difference between associative arrays and multidimensional arrays?

Associative array — An array where each key has its own specific value. Multidimensional array — An array containing one or more arrays within itself.

What is the difference between Indexed and associative array in PHP?

There are two kinds of arrays in PHP: indexed and associative. The keys of an indexed array are integers, beginning at 0. Indexed arrays are used when you identify things by their position. Associative arrays have strings as keys and behave more like two-column tables.


2 Answers

Under the surface, the two approaches are equivalent. However, you get most of the standard OO benefits when using a class: encapsulation, inheritance, etc.

Also, look at the following examples:

$arr['naem'] = 'John'; 

is perfectly valid and could be a difficult bug to find.

On the other hand,

$class->setNaem('John'); 

will never work.

like image 105
Zack Marrapese Avatar answered Sep 28 '22 13:09

Zack Marrapese


A simple class like this one:

class PersonalData {     protected $firstname;     protected $lastname;      // Getters/setters here } 

Has few advantages over an array.

  1. There is no possibility to make some typos. $data['firtsname'] = 'Chris'; will work while $data->setFirtsname('Chris'); will throw en error.
  2. Type hinting: PHP arrays can contain everything (including nothing) while well defined class contains only specified data.

    public function doSth(array $personalData) {     $this->doSthElse($personalData['firstname']); // What if "firstname" index doesn't exist? }   public function doSth(PersonalData $personalData) {     // I am guaranteed that following method exists.      // In worst case it will return NULL or some default value     $this->doSthElse($personalData->getFirstname()); } 
  3. We can add some extra code before set/get operations, like validation or logging:

    public function setFirstname($firstname) {     if (/* doesn't match "firstname" regular expression */) {         throw new InvalidArgumentException('blah blah blah');     }   
    if (/* in debbug mode */) {     log('Firstname set to: ' . $firstname); }   $this->firstname = $firstname; 
    }
  4. We can use all the benefits of OOP like inheritance, polymorphism, type hinting, encapsulation and so on...
  5. As mentioned before all of our "structs" can inherit from some base class that provides implementation for Countable, Serializable or Iterator interfaces, so our structs could use foreach loops etc.
  6. IDE support.

The only disadvantage seems to be speed. Creation of an array and operating on it is faster. However we all know that in many cases CPU time is much cheaper than programmer time. ;)

like image 29
Crozin Avatar answered Sep 28 '22 12:09

Crozin