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[\'f
Just add implements ArrayAccess
to your class and add the required methods:
See http://php.net/manual/en/class.arrayaccess.php
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 could also cast the object as an array:
if((array)$obj['foo'] == 'bar'){
//more code here
}