介紹: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);
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);

浙公網安備 33010602011771號