PHP object like array

Viewed 26962

I need to be able to set my object like this:

$obj->foo = 'bar';

then I need to use it as an array like that:

if($obj['foo'] == 'bar'){
  //more code here
}
9 Answers

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
}

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're mixing objects and arrays. You can create and access an object like so:

$obj = new stdClass;
$obj->foo = 'bar';

if($obj->foo == 'bar'){
// true
}

and an array like so:

$obj = new Array();
$obj['foo'] = 'bar';

if($obj['foo'] == 'bar'){
// true
}

You can define a class and add implements ArrayAccess if you want to access your class as both an array and a class.

http://www.php.net/manual/en/language.oop5.php

Your object must implement the ArrayAccess interface, then PHP will allow you to use the square brackets like that.

You could also cast the object as an array:

if((array)$obj['foo'] == 'bar'){
  //more code here
}
Related