介绍: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);
标签:
PHP
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架