Skip to content

Instantly share code, notes, and snippets.

@Ekstazi
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ekstazi/10741133 to your computer and use it in GitHub Desktop.
Save Ekstazi/10741133 to your computer and use it in GitHub Desktop.
Proper Array object
<?
/**
* Object do same as raw array in php(contract with ArrayObject):
* $a[][]='a';
* $a['b'][]='c';
* $a['b'][][]='d';
*/
class ProperObjectArray implements \ArrayAccess, \Countable,\IteratorAggregate{
protected $_array=[];
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Whether a offset exists
* @link http://php.net/manual/en/arrayaccess.offsetexists.php
* @param mixed $offset <p>
* An offset to check for.
* </p>
* @return boolean true on success or false on failure.
* </p>
* <p>
* The return value will be casted to boolean if non-boolean was returned.
*/
public function offsetExists($offset)
{
return isset($this->_array[$offset]);
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Offset to retrieve
* @link http://php.net/manual/en/arrayaccess.offsetget.php
* @param mixed $offset <p>
* The offset to retrieve.
* </p>
* @return mixed Can return all value types.
*/
public function &offsetGet($offset)
{
if(isset($offset))
// return reference to this el
return $this->_array[$offset];
// for proper subindex, ex. $a[][]='t'
else {
// create new empty var
// and append array this this var reference, then return it
$t=null;
return $this->_array[]=&$t;
}
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Offset to set
* @link http://php.net/manual/en/arrayaccess.offsetset.php
* @param mixed $offset <p>
* The offset to assign the value to.
* </p>
* @param mixed $value <p>
* The value to set.
* </p>
* @return void
*/
public function offsetSet($offset, $value)
{
// если указан ключ
if(isset($offset))
$this->_array[$offset]=$value;
else
// иначе дописываем
$this->_array[]=$value;
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Offset to unset
* @link http://php.net/manual/en/arrayaccess.offsetunset.php
* @param mixed $offset <p>
* The offset to unset.
* </p>
* @return void
*/
public function offsetUnset($offset)
{
unset($this->_array[$offset]);
}
/**
* (PHP 5 &gt;= 5.1.0)<br/>
* Count elements of an object
* @link http://php.net/manual/en/countable.count.php
* @return int The custom count as an integer.
* </p>
* <p>
* The return value is cast to an integer.
*/
public function count()
{
return count($this->_array);
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Retrieve an external iterator
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php
* @return Traversable An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
*/
public function getIterator()
{
return new \ArrayIterator($this->_array);
}
/**
* @return array
*/
public function toArray()
{
return $this->_array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment