Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ObjectArray: Adapter To Access Arrays As Objects

DZone's Guide to

ObjectArray: Adapter To Access Arrays As Objects

·
Free Resource
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 ≥t($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) . ']';
	}
}
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}