• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

介绍:SPL - Standard PHP Library(一)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

目的:介绍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);

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
新浪微博LAMP性能优化之路 - PHP性能优化发布时间:2022-07-10
下一篇:
配置WindowsServer2008+iis+php+mysql所需下载安装包发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap