PHP object like array

ArrayObject implements the ArrayAccess interface (and some more). Using the ARRAY_AS_PROPS flag it provides the functionality you're looking for.

$obj = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS);
$obj->foo = 'bar';
echo $obj['foo'];

Alternatively you can implement the ArrayAccess interface in one of your own classes:

class Foo implements ArrayAccess {
  public function offsetExists($offset) {
    return isset($this->$offset);
  }

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

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

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

$obj = new Foo;
$obj->foo = 'bar';
echo $obj['foo'];

You'll have to implement the ArrayAccess interface to be able to do that -- which only means implementing a few (4 to be exact) simple methods :

  • ArrayAccess::offsetExists : Whether or not an offset exists.
  • ArrayAccess::offsetGet : Returns the value at specified offset.
  • ArrayAccess::offsetSet : Assigns a value to the specified offset.
  • and ArrayAccess::offsetUnset : Unsets an offset.

There is a full example on the manual's page I pointed to ;-)


Just add implements ArrayAccess to your class and add the required methods:

  • public function offsetExists($offset)
  • public function offsetGet($offset)
  • public function offsetSet($offset, $value)
  • public function offsetUnset($offset)

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


Try extending ArrayObject

You'll also need to implement a __get Magic Method as Valentin Golev mentioned.

Your class will need to looks something like this:

Class myClass extends ArrayObject {
    // class property definitions...
    public function __construct()
    {
        //Do Stuff
    }

    public function __get($n) { return $this[$n]; }

    // Other methods
}

Tags:

Php

Arrays