3v4l.org

run code in 300+ PHP versions simultaneously
<?php class ArrayStorage implements Iterator, ArrayAccess { private $holder = []; private $instanceName; public function __construct($instanceName) { if (!class_exists($instanceName)) { throw new \Exception('Class '.$instanceName.' was not found'); } $this->instanceName = $instanceName; } public function rewind() { reset($this->holder); } public function current() { return current($this->holder); } public function key() { return key($this->holder); } public function next() { next($this->holder); } public function valid() { return false !== $this->current(); } public function offsetSet($offset, $value) { if (!($value instanceof $this->instanceName)) { throw new \Exception('Storage allows only '.$this->instanceName.' instances'); } if (is_null($offset)) { $this->holder[] = $value; } else { $this->holder[$offset] = $value; } } public function offsetExists($offset) { return isset($this->holder[$offset]); } public function offsetUnset($offset) { unset($this->holder[$offset]); } public function offsetGet($offset) { return isset($this->holder[$offset]) ? $this->holder[$offset] : null; } } class Foo {} class Bar {} $storage = new ArrayStorage('Foo'); $storage[] = new Foo; $storage['baz'] = new Foo; //var_export($storage); foreach ($storage as $key => $value) { echo($key. ' => '.PHP_EOL.var_export($value, 1).PHP_EOL); } $storage['bee'] = new Bar;

preferences:
33.5 ms | 409 KiB | 5 Q