Skip to content

Instantly share code, notes, and snippets.

@tugrul
Created June 17, 2015 15:52
Show Gist options
  • Select an option

  • Save tugrul/14a621181a2e96ac9d81 to your computer and use it in GitHub Desktop.

Select an option

Save tugrul/14a621181a2e96ac9d81 to your computer and use it in GitHub Desktop.

Revisions

  1. tugrul created this gist Jun 17, 2015.
    96 changes: 96 additions & 0 deletions arrayobject.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,96 @@
    <?php

    class MyArrayObject extends \ArrayObject
    {
    public function offsetGet($index)
    {
    if (!parent::offsetExists($index)) {
    parent::offsetSet($index, new MyArrayObject(array(), \ArrayObject::ARRAY_AS_PROPS));
    }

    return parent::offsetGet($index);
    }

    // this magic method not called on non-exist property access
    public function __get($index)
    {
    return $this->offsetGet($index);
    }
    }


    $arrObj1 = new \MyArrayObject(array(), \ArrayObject::ARRAY_AS_PROPS);


    // error: undefined index foo BP_VAR_RW
    $arrObj1->foo->bar->baz = 99;

    // OK
    $bar = $arrObj1->foo->bar;
    $bar->baz = 99;

    // OK
    $arrObj1['foo']['bar']['baz'] = 99;




    class OtherArrayObject implements \ArrayAccess
    {
    private $storage = array();


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

    public function offsetGet($offset)
    {
    if (!$this->offsetExists($offset)) {
    $this->offsetSet($offset, new OtherArrayObject());
    }

    return $this->storage[$offset];
    }

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

    public function offsetUnset($offset)
    {
    unset($this->storage[$offset]);
    }

    public function __get($name)
    {
    return $this->offsetGet($name);
    }

    public function __set($name, $value)
    {
    return $this->offsetSet($name, $value);
    }

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

    public function __unset($name)
    {
    unset($this->storage[$name]);
    }
    }

    $arrObj2 = new OtherArrayObject();

    // OK:
    $arrObj2->foo->bar->baz = 99;

    // OK:
    $arrObj2['foo']['bar']['baz'] = 99;

    var_dump($arrObj2);