3v4l.org

run code in 300+ PHP versions simultaneously
<?php class GenericCollection { private $className; private $items = []; public function __construct($className, $data = []) { if (!class_exists($className)) { throw new \LogicException('Invalid class name: ' . $className); } $this->className = $className; 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 push($item) { $this->checkItemIsInstanceOfCorrectClass($item); array_push($this->items, $item); } public function unshift($item) { $this->checkItemIsInstanceOfCorrectClass($item); array_unshift($this->items, $item); } // other collection methods } class Foo {} $col = new GenericCollection(Foo::class, [new Foo, new Foo]);

preferences:
25.18 ms | 402 KiB | 5 Q