简体   繁体   中英

Collection of objects of an specific class in PHP

I would like to have an array/object-like collection in which the elements are objects of an specific class (or derived from it). In Java I would do something like the following:

private List<FooClass> FooClassBag = new ArrayList<FooClass>();

I know that this could and will tightly couple some components of my application, but I have been wondering for a while now how to do that in a proper way.

The only way to do it I can think now is to create a class implementing Countable , IteratorAggregate , ArrayAccess ... and forcing a way to add elements of just one class, but is this the best way to do that?

Here's a possible implementation, but I wouldn't ever 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM