PHP中特定类的对象集合

Die*_*lló 3 php collections

我想有一个数组/类似对象的集合,其中元素是特定类的对象(或从中派生).在Java中,我会做类似以下的事情:

private List<FooClass> FooClassBag = new ArrayList<FooClass>();
Run Code Online (Sandbox Code Playgroud)

我知道这可以并且将紧密地耦合我的应用程序的一些组件,但我一直想知道如何以适当的方式做到这一点.

要做到这一点我现在想的唯一方法是创建一个类实现Countable,IteratorAggregate,ArrayAccess...和强迫的方式来增加只是一个类的元素,但是这是做的最好的方法?

Wal*_*han 5

这是一个可能的实现,但我不会使用这样的结构.

<?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;
}
Run Code Online (Sandbox Code Playgroud)

  • @DiegoAgulló尝试在动态类型语言上强制使用静态类型的数据结构是没有意义的.让PHP变得有意义也毫无意义. (4认同)