DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
ObjectArray: Adapter To Access Arrays As Objects
Allows accessing array elements as an object, when the element doesn't exist it returns null instead of raising notices.
Usage:
$data = new ObjectArray($_POST); echo $data->name; echo $data['name'];
Code:
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
class ObjectArray implements IteratorAggregate, ArrayAccess, Countable{
protected $list;
public function __construct(&$list = null, $byReference = true){
is_array($list) || $list = array();
$this->setArray($list, $byReference);
}
public function getArray(){
return $this->list;
}
public function setArray(&$list = null, $byReference = true){
if(!is_array($list))
throw new Exception('Array expected');
$byReference ? $this->list = &$list : $this->list = $list;
}
public function &__get($n){
return $this->get($n);
}
public function __isset($n){
return isset($this->list[$n]);
}
public function __unset($n){
unset($this->list[$n]);
}
public function __set($n, $v){
$this->set($n, $v);
}
public function &get($n, $default = null){
if(isset($this->$n))
return $this->list[$n];
return $default;
}
public function set($n, $value){
$n === null ? $this->list[] = $value : $this->list[$n] = $value;
}
//Countable
public function count(){
return count($this->list);
}
//IteratorAggregate
public function getIterator(){
return new ArrayIterator($this->list);
}
//ArrayAccess
public function offsetExists($n){
return isset($this->list[$n]);
}
public function offsetGet($n){
return $this->get($n);
}
public function offsetSet($n, $v){
$this->set($n, $v);
}
public function offsetUnset($n){
unset($this->list[$n]);
}
public function __toString(){
return '[' . get_class($this) . '@' . spl_object_hash($this) . ']';
}
}





Comments
Snippets Manager replied on Wed, 2009/01/28 - 11:40am