Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Created January 2, 2025 14:38
Show Gist options
  • Save ziadoz/e601fe69a1dcdd0be5d2222d405f1626 to your computer and use it in GitHub Desktop.
Save ziadoz/e601fe69a1dcdd0be5d2222d405f1626 to your computer and use it in GitHub Desktop.
PHP- Iterable Object
<?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