<?php
// create object setting data by array
$myArray = array('apple' => 'red', 'pear' => 'green', 'lemon' => 'yellow', 'apricot' => 'orange' );
$myObject = new MyObject($myArray);
// create object setting data by magic method __set()
$myObject = new MyObject();
$myObject->apple = 'red';
$myObject->pear = 'green';
$myObject->lemon = 'yellow';
$myObject->apricot = 'orange';
class MyObject implements ArrayAccess, Countable, IteratorAggregate
{
/**
* If set to true Exception will be thrown when attribute not found
*
* @var boolean
*/
protected $_throwException;
/**
* Data structure where attributes will be stored
*
* @var stdClass
*/
protected $data;
public function __construct($values = null, $throwException = true)
{
$this->data = $this->resetAttributes();
$this->setFromArray($values);
}
$this->setThrowException($throwException);
}
public function __get($attribute) {
if (!isset($this->data->$attribute)) {
if ($this->_throwException) {
throw new Exception('Attribute ' . $attribute . ' is not set');
} else {
return null;
}
}
return $this->data->$attribute;
}
public function __set($key, $value)
{
$this->data->$key = $value;
}
public function getAttributes()
{
$attributes = $this->data;
return $attributes;
}
public function resetAttributes() {
$this->data = new stdClass();
}
public function setFromArray
(array $array) {
foreach ($array as $k => $v) {
$v = new self($v, $this->getThrowException());
}
$this->data->$k = $v;
}
return $this;
}
public function setThrowException($bool) {
$this->_throwException = (bool) $bool;
return $this;
}
public function toArray()
{
$attributes = $this->getAttributes();
foreach ($attributes as $k => $v) {
$array[$k] = $v;
}
return $array;
}
public function getThrowException()
{
return $this->_throwException;
}
public function offsetExists($offset) {
return isset($this->data->$offset);
}
public function offsetGet($offset) {
return $this->data->$offset;
}
public function offsetSet($offset, $value) {
$this->data->$offset = $value;
}
public function offsetUnset($offset) {
unset($this->data->$offset);
}
{
return count($this->toArray());
}
public function getIterator()
{
return $this->getAttributes();
}
}