2

I am trying to store an array and manipulate that array using a custom class that extends ArrayObject.

class MyArrayObject extends ArrayObject {
    protected $data = array();

    public function offsetGet($name) {
        return $this->data[$name];
    }

    public function offsetSet($name, $value) {
        $this->data[$name] = $value;
    }

    public function offsetExists($name) {
        return isset($this->data[$name]);
    }

    public function offsetUnset($name) {
        unset($this->data[$name]);
    }
}

The problem is if I do this:

$foo = new MyArrayObject();
$foo['blah'] = array('name' => 'bob');
$foo['blah']['name'] = 'fred';
echo $foo['blah']['name'];

The output is bob and not fred. Is there any way I can get this to work without changing the 4 lines above?

1 Answer 1

3

This is a known behaviour of ArrayAccess ("PHP Notice: Indirect modification of overloaded element of MyArrayObject has no effect" ...).

http://php.net/manual/en/class.arrayaccess.php

Implement this in MyArrayObject:

public function offsetSet($offset, $data) {
    if (is_array($data)) $data = new self($data);
    if ($offset === null) {
        $this->data[] = $data;
    } else {
        $this->data[$offset] = $data;
    }
} 
Sign up to request clarification or add additional context in comments.

2 Comments

The problem with that is arrays are stored as objects so if I set an array of values, I then have to call toArray() before looping through them.
@fire Implement Iterator and Countable maybe?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.