Skip to content

Instantly share code, notes, and snippets.

@ranacseruet
Last active October 21, 2023 16:31
Show Gist options
  • Save ranacseruet/5f7b5dc1eb0240490307 to your computer and use it in GitHub Desktop.
Save ranacseruet/5f7b5dc1eb0240490307 to your computer and use it in GitHub Desktop.
PHP Dynamic Object With Array and Iterative access capability
<?php
class PDAO implements \ArrayAccess, \Iterator
{
/**
* @var array data
*/
protected $data = array();
/**
* Constructor - Create a new object, or load an existing one from data.
*
* @param array $doc data array.
*/
public function __construct(array $doc = array())
{
$this->data = $doc;
foreach ($doc as $key => $value) {
$this[$key] = $value;
}
}
/**
* Checks whether a key is set on this object.
*
* @param string $key The key.
* @return bool
*/
public function __isset($key)
{
return isset($this->data[$key]);
}
/**
* Get the value of a key in this object.
*
* @param string $key The key.
* @return mixed
*/
public function __get($key)
{
if(isset($this->data[$key]))
{
return $this->data[$key];
}
else
{
return null;
}
}
/**
* Set the value of a key in this object.
*
* @param string $key The key.
* @param string $value The value.
*/
public function __set($key, $value)
{
if ($key === null) {
$this->data[] = $value;
} else {
$this->data[$key] = $value;
}
}
/**
* Unset a property in this object
* @param type $name
*/
public function __unset($name)
{
if(isset($this->data[$name]))
{
unset($this->data[$name]);
}
}
/**
* Check if a key exist
* @param type $offset
* @return type
*/
public function offsetExists($offset)
{
return $this->__isset($offset);
}
/**
* get value for a key
* @param type $offset
* @return type
*/
public function offsetGet($offset)
{
return $this->__get($offset);
}
/**
* set value for a key
* @param type $offset
* @param type $data
* @return type
*/
public function offsetSet($offset, $data)
{
if (is_array($data)) {
$data = new self($data);
}
$this->__set($offset, $data);
}
/**
* unset a key
* @param type $offset
*/
public function offsetUnset($offset)
{
unset($this->data[$offset]);
}
/**
* Reset index
* @return type
*/
function rewind() {
return reset($this->data);
}
/**
* Return current data
* @return type
*/
function current() {
return current($this->data);
}
/**
* Return current key
* @return type
*/
function key() {
return key($this->data);
}
/**
* Return next key
* @return type
*/
function next() {
return next($this->data);
}
/**
* checks whether current element is valid
* @return type
*/
function valid() {
return key($this->data) !== null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment