介绍:SPL - Standard PHP Library(一)

目的:介绍IteratorAggregate,Countable,ArrayAccess

当一个类内部维护或封装着一个数组,我们可以通过IteratorAggregate,Countable,ArrayAccess这3个接口来进行相应的操作。通过IteratorAggregate接口,外部可以对该数组进行迭代操作;通过Countable接口外部可以知道该数组含有多少对象;通过ArrayAccess可以对数据进行增删改查等相应操作。

 

 

代码
1 class Test implements IteratorAggregate,Countable,ArrayAccess {
2
3 protected $_ary = array();
4
5 //IteratorAggregate中的抽象方法,用于数组迭代
6   public function getIterator() {
7 return new ArrayObject($this->_ary);
8 }
9 //Countable中的抽象方法,用于得到数组中对象数量
10   public function count() {
11 return count($this->_ary);
12 }
13
14 public function offsetExists ($offset) {
15 return array_key_exists($offset,$this->_ary);
16 }
17
18 //ArrayAccess中的抽象方法,用于得到数组中某个对象
19   public function offsetGet ($offset) {
20 if($this->offsetExists($offset)) {
21 return $this->_ary[$offset];
22 }
23 else {
24 return 'null';
25 }
26 }
27
28 //ArrayAccess中的抽象方法,用于为数组添加或更新值
29   public function offsetSet ($offset, $value) {
30 $this->_ary[$offset] = $value;
31 }
32
33 //ArrayAccess中的抽象方法,用于清理数组某项
34   public function offsetUnset ($offset) {
35 unset($this->_ary[$offset]);
36 }
37 }

 

测试代码
 1 $t = new Test();
 2  /*
 3 为Test类中的数组赋值
 4  */
 5  $t->offsetSet(1, 1);
 6  $t->offsetSet(2, 2);
 7  $t->offsetSet(3, 3);
 8  $t->offsetSet(4, 4);
 9 
10  /*
11 迭代Test类中的数组
12 显示:
13 1=>1
14 2=>2
15 3=>3
16 4=>4
17  */
18  foreach($t as $key => $value) {
19     echo $key.'=>'.$value;
20     echo '<br />';
21 }
22  /*
23 显示:
24 4
25  */
26  echo count($t);
27  echo '<br/>';
28  /*
29 显示:
30 1
31  */
32  echo $t->offsetExists(4);
33  echo '<br/>';
34  /*
35 显示:
36 4
37  */
38  echo $t->offsetGet(4);
39  echo '<br/>';
40  echo $t->offsetUnset(4);
41  /*
42 显示:
43 null
44  */
45  echo $t->offsetGet(4);
posted @ 2009-12-06 23:55  Miser  阅读(1082)  评论(0编辑  收藏  举报