Skip to content

Instantly share code, notes, and snippets.

@jmsfwk
Created November 16, 2016 10:12
Show Gist options
  • Save jmsfwk/b7b294d861f2e8ffa3a6db1b6627bdcd to your computer and use it in GitHub Desktop.
Save jmsfwk/b7b294d861f2e8ffa3a6db1b6627bdcd to your computer and use it in GitHub Desktop.
Single type array class in PHP
<?php
final class List implements ArrayAccess
{
protected $type;
protected $array = [];
function __construct($var)
{
$this->type = $this->getType($var);
}
protected function getType($var): string
{
$type = gettype($var);
if ($type != 'object') {
return $type;
}
return get_class($var);
}
public function offsetExists($offset)
{
return array_key_exists($offset, $this->array);
}
public function offsetGet($offset)
{
return $this->array[$offset];
}
public function offsetSet($offset, $value)
{
if($this->type != $this->getType($value)){
$reflection = new ReflectionMethod($this, __FUNCTION__);
throw new TypeError(sprintf(
'Argument passed to %s must be an instance of %s, %s given on line %s',
__class__,
$this->type,
$this->getType($value),
$reflection->getStartLine()
));
}
$this->array[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->array[$offset]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment