- array_push: documentation ( source)
- class_exists: documentation ( source)
- array_unshift: documentation ( source)
<?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]);