3v4l.org

run code in 300+ PHP versions simultaneously
<?php class GenericCollection extends \SplDoublyLinkedList { private $className; public function __construct($className, $data = []) { if (!class_exists($className)) { throw new \LogicException('Invalid class name: ' . $className); } $this->className = $className; $this->items = new \SplDoublyLinkedList; foreach ($data as $item) { $this->push($item); } } private function checkItemIsInstanceOfCorrectClass($item) { if (!$item instanceof $this->className) { throw new \LogicException('Items in this collection must be instances of ' . $this->className); } } public function getClassName() { return $this->className; } public function add($item) { $this->checkItemIsInstanceOfCorrectClass($item); parent::add($item); } public function push($item) { $this->checkItemIsInstanceOfCorrectClass($item); parent::push($item); } public function unshift($item) { $this->checkItemIsInstanceOfCorrectClass($item); parent::unshift($item); } public function offsetSet($offset, $item) { $this->checkItemIsInstanceOfCorrectClass($item); parent::offsetSet($offset, $item); } } class Foo {} class Bar {} $col = new GenericCollection(Foo::class, [new Foo, new Foo]); $col->push(new Foo); $col[] = new Foo; foreach ($col as $foo) { var_dump($foo); } $col->push(new Bar);

preferences:
35.29 ms | 402 KiB | 5 Q