3v4l.org

run code in 300+ PHP versions simultaneously
<?php final class Collection { /** @var string */ private $type; private $objects = []; /** * @param string $type * @return Collection */ public static function ofType($type) { $collection = new static(); $collection->type = $type; $class = explode('\\', $type); class_alias(self::class, sprintf('%sCollection', array_pop($class))); return $collection; } public function add($object) { if (!$object instanceof $this->type) { throw new Exception(sprintf('Object of type [%s] is not [%s]', get_class($object), $this->type)); } $this->objects[] = $object; } public function getAll() { return $this->objects; } } final class Person {} $col = Collection::ofType(Person::class); $col->add($person); function parsePersonCollection(PersonCollection $coll) { var_dump($coll->getAll()); } parsePersonCollection($col);

preferences:
53.68 ms | 402 KiB | 5 Q