Skip to content

Instantly share code, notes, and snippets.

@bshaffer
Forked from anonymous/gist:234678
Created May 25, 2010 16:19
Show Gist options
  • Save bshaffer/413344 to your computer and use it in GitHub Desktop.
Save bshaffer/413344 to your computer and use it in GitHub Desktop.
PHP Object Oriented Array class
<?php
class A implements ArrayAccess, Iterator, Countable
{
public function __construct($arr) {
$this->arr = is_array($arr) ? $arr : func_get_args();
}
public function __toString() {
return print_r($this->arr, true);
}
public function to_a(){
return $this->arr;
}
public function each(Closure $fun) {
foreach ($this->arr as $key => $value)
$fun($value, $key);
}
public function reduce(Closure $fun) {
$new = array();
foreach ($this->arr as $key => $value) {
if($fun($value, $key))
$new[$key] = $value;
}
return $new;
}
public function map(Closure $fun) {
$new = array();
foreach ($this->arr as $key => $value)
$new[$key] = $fun($value, $key);
return $new;
}
public function until(Closure $fun) {
foreach ($this->arr as $key => $value){
if($fun($value, $key))
return $key;
}
return false;
}
public function __call($name, $args) {
if(strpos($name, '_') === 0 && is_callable(array($this, substr($name, 1)))) { // leading underscore denotes array reference
$ret = call_user_func_array(array($this, substr($name, 1)), $args);
if (is_array($ret))
$this->arr = $ret;
return $ret;
}
throw new Exception('Call to undefined method '.get_class($this).'::'.$name);
}
public function __invoke($i, $length = null) {
if (!array_key_exists($i, $this->arr))
return null;
if (is_null($length))
return $this->arr[$i];
return array_slice($this->arr, $i, $length);
}
public function offsetSet($offset,$value) {
if ($offset == "") {
$this->arr[] = $value;
}else {
$this->arr[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->arr[$offset]);
}
public function offsetUnset($offset) {
unset($this->arr[$offset]);
}
public function offsetGet($offset) {
return isset($this->arr[$offset]) ? $this->arr[$offset] : null;
}
public function rewind() {
reset($this->arr);
}
public function current() {
return current($this->arr);
}
public function key() {
return key($this->arr);
}
public function next() {
return next($this->arr);
}
public function valid() {
return $this->current() !== false;
}
public function count() {
return count($this->arr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment