php 对象集合 查询,PHP中特定类的对象集合

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

private List FooClassBag = new ArrayList();

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

我能想到的唯一方法是创建一个实现Countable,IteratorAggregate,ArrayAccess …的类,并强制添加一个类的元素,但这是最好的方法吗?

解决方法:

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

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;

}

标签:php,collections

来源: https://codeday.me/bug/20190901/1781730.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值