Created
January 2, 2025 14:38
-
-
Save ziadoz/e601fe69a1dcdd0be5d2222d405f1626 to your computer and use it in GitHub Desktop.
PHP- Iterable Object
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 | |
use ArrayAccess; | |
use Countable; | |
use IteratorAggregate; | |
use Traversable; | |
class Items implements ArrayAccess, Countable, IteratorAggregate | |
{ | |
public function __construct(protected array $items = []) | |
{ | |
} | |
public function offsetExists(mixed $offset): bool | |
{ | |
return isset($this->items[$offset]); | |
} | |
public function offsetGet(mixed $offset): mixed | |
{ | |
return $this->items[$offset]; | |
} | |
public function offsetSet(mixed $offset, mixed $value): void | |
{ | |
if (is_null($offset)) { | |
$this->items[] = $value; | |
} else { | |
$this->items[$offset] = $value; | |
} | |
} | |
public function offsetUnset(mixed $offset): void | |
{ | |
return unset($this->items[$offset]); | |
} | |
public function count(): int | |
{ | |
return count($this->items); | |
} | |
public function getIterator(): Traversable | |
{ | |
return yield from $this->items; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment