$collection = new PostCollection(); $collection[] = new Post(1); $collection[] = 'abc'; foreach ($collection as $item) { echo $item->getId(); }
class PostCollection extends ArrayIterator { public function current() : ?Post { /* … */ } public function offsetGet(mixed $key) : ?Post { /* … */ } public function offsetSet(mixed $key, mixed $value): void { if (! $value instanceof Post) { throw new InvalidArgumentException("…"); } // … } }
$posts = []; $posts[] = 1; $posts[] = 'string';
$posts = [];