Created
July 31, 2021 23:30
-
-
Save otakupahp/efb8bff22cb8a362c44c2027caf19835 to your computer and use it in GitHub Desktop.
Create an iterrator collection that could be accesed as an array
This file contains 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 | |
class Collection implements Iterator, ArrayAccess | |
{ | |
private int $position; | |
private array $array = []; | |
public function __construct() { | |
$this->position = 0; | |
} | |
public function current(): mixed { | |
return $this->array[$this->position]; | |
} | |
public function next(): void { | |
++$this->position; | |
} | |
public function key(): int { | |
return $this->position; | |
} | |
public function valid(): bool { | |
return array_key_exists($this->position, $this->array); | |
} | |
public function rewind(): void { | |
$this->position = 0; | |
} | |
public function offsetExists($offset): bool { | |
return array_key_exists($offset, $this->array); | |
} | |
public function offsetGet($offset): mixed { | |
return $this->array[$offset] ?? null; | |
} | |
public function offsetSet($offset, $value): void { | |
if (is_null($offset)) { | |
$this->array[] = $value; | |
} else { | |
$this->array[$offset] = $value; | |
} | |
} | |
public function offsetUnset($offset): void { | |
unset($this->array[$offset]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment