Value of 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(
        'name'=>"Green Fred");


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?

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,


will never work.