Created
January 16, 2014 19:55
-
-
Save dongilbert/8462216 to your computer and use it in GitHub Desktop.
Abstract ArrayOf Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class ArrayOf implements ArrayAccess, Iterator | |
{ | |
protected $type = null; | |
protected $data = []; | |
protected $index = 0; | |
public function __construct() | |
{ | |
if (is_null($this->type)) { | |
throw new Exception('Extending classes must specify a type.'); | |
} | |
} | |
public function offsetExists($offset) | |
{ | |
return isset($this->data[$offset]); | |
} | |
public function offsetGet($offset) | |
{ | |
return $this->data[$offset]; | |
} | |
public function offsetSet($offset, $value) | |
{ | |
if ($value instanceof $this->type) { | |
$this->data[$offset] = $value; | |
} else { | |
$type = is_object($value) ? get_class($value) : gettype($value); | |
throw new UnexpectedValueException( | |
sprintf('Value must be of type %s, %s given.', $this->type, $type) | |
); | |
} | |
} | |
public function offsetUnset($offset) | |
{ | |
unset($this->data[$offset]); | |
} | |
public function current() | |
{ | |
return $this->data[$this->index]; | |
} | |
public function next() | |
{ | |
++$this->index; | |
} | |
public function key() | |
{ | |
return $this->index; | |
} | |
public function valid() | |
{ | |
return isset($this->data[$this->index]); | |
} | |
public function rewind() | |
{ | |
$this->index = 0; | |
} | |
} | |
class ArrayOfFoo extends ArrayOf | |
{ | |
protected $type = 'Foo'; | |
} | |
class Foo | |
{ | |
public function doSomething($i) | |
{ | |
echo $i . PHP_EOL; | |
} | |
} | |
$fooArray = new ArrayOfFoo; | |
for ($i=0; $i<100; $i++) { | |
$fooArray[$i] = new Foo; | |
} | |
function needsFooArray(ArrayOfFoo $fooArray) { | |
foreach ($fooArray as $i => $foo) { | |
$foo->doSomething($i); | |
} | |
} | |
needsFooArray($fooArray); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment