- var_dump: documentation ( source)
- class_alias: documentation ( source)
- explode: documentation ( source)
- array_pop: documentation ( source)
- sprintf: documentation ( source)
<?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);