Created
          November 16, 2016 10:12 
        
      - 
      
- 
        Save jmsfwk/b7b294d861f2e8ffa3a6db1b6627bdcd to your computer and use it in GitHub Desktop. 
    Single type array class in PHP
  
        
  
    
      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 | |
| 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