我希望有一个类似数组/对象的集合,其中的元素是特定类(或从中派生)的对象。在Java中,我会做如下的事情:
private List<FooClass> FooClassBag = new ArrayList<FooClass>();
我知道这可以并且将紧密地耦合我的应用程序的一些组件,但是我已经想了一段时间了,现在如何以一种正确的方式做到这一点。
我想现在做的唯一方法是创建一个类,实现
Countable
,cc,IteratorAggregate
…强制添加一个类的元素,但这是最好的方法吗? 最佳答案
这里有一个可能的实现,但我永远不会使用这样的结构。
<?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;
}