Search code examples
phparraysarrayobject

When is it appropriate to use an ArrayObject instead of an Array


I'm wondering when, if ever it would be appropriate to use an ArrayObject() instead of an Array()? Here's an example i've been working on.

To me i'm thinking a simple array will work, but i found ArrayObject() in the manual and I'm wondering, if it would be better to use one instead of a simple array.

public function calculateTotal(){
    if(count($this->items) > 0){
        $n = 0;
        foreach($this->items as $item){
            if($item->size == 'small'){
                $k = $item->price->small;
            }
            if($item->size == 'large'){
                $k = $item->price->large;
            }
            $n += $k * $item->quantity;
        }
    }else{
        $n = 0;
    }
    return (int) $n;
}

Now I'm confused as to how i should construct the object.

for instance can i construct it with the short array syntax?

$this->items = []; //empty object

or should i construct is as an Array object

$this->items = new ArrayObject(); //empty object

I'm also confused as to how exactly i should push new items to the array.

i have the following function i'm writing:

Also how should i append arrray objects to this object?

is this good?

public function additem($item){
        $add = [
        'item_id'=>$this->item_id(),
        'name'=>$item['name'],
        'size',$item['size'],
        'quantity'=>$item['quantity'],
        'price'=>[
            'large'=>$item['price'],
            'small'=>$item['price']
            ]
        ]
        array_push($this->items,$add);
}

or should i instead use ArrayObject::append() or some other method?

I checked the manual and it says this:

public void ArrayObject::append ( mixed $value )
Appends a new value as the last element.

Note:
This method cannot be called when the ArrayObject was constructed from an object. Use ArrayObject::offsetSet() instead.

source http://php.net/manual/en/arrayobject.append.php

The reason i'm asking this now is, later on when needing to delete items from this list how will i find what i'm looking for? can i use in_array() on this object.

I apologize in advance for these questions that might seem dumb to you, but keep in mind I'm still learning some of the more technical things. Thank you


Solution

  • There's nothing in your first snippet that would require ArrayObject. KISS and use simple arrays: array_push($this->items,$add); or $this->items []= $add; are both fine.

    As a side note, there's a discrepancy between calculateTotal and add in your code: you have to decide whether you want your item structures to be arrays ($item['price']) or objects ($item->price). My advice is to use arrays, but that's really up to you.