Collection of objects of a specific class in PHP
I would like to have an array / object-like collection in which the elements are objects of a certain class (or derived from it). In Java, I would do the following:
private List<FooClass> FooClassBag = new ArrayList<FooClass>();
I know this can and will tightly couple some components of my application, but I wondered for a while how to do this properly.
The only way to do it, I can now think about creating a class that implements Countable
, IteratorAggregate
, ArrayAccess
... and the crossing of ways to add elements of only one class, but this is the best way to do this?
+3
source to share
1 answer
Here is a possible implementation, but I would never use such a structure.
<?php
class TypedList implements \ArrayAccess, \IteratorAggregate {
private $type;
private $container = array();
public function __construct($type) {
$this->type = $type;
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return $this->container[$offset];
}
public function offsetSet($offset, $value) {
if (!is_a($value, $this->type)) {
throw new \UnexpectedValueException();
}
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function getIterator() {
return new \ArrayIterator($this->container);
}
}
class MyClass {
private $value;
public function __construct($value) {
$this->value = $value;
}
public function __toString() {
return $this->value;
}
}
class MySubClass extends MyClass {}
$class_list = new TypedList('MyClass');
$class_list[] = new MyClass('foo');
$class_list[] = new MySubClass('bar');
try {
$class_list[] = 'baz';
} catch (\UnexpectedValueException $e) {
}
foreach ($class_list as $value) {
echo $value . PHP_EOL;
}
+5
source to share