Home  >  Article  >  Backend Development  >  php迭代器,php代器_PHP教程

php迭代器,php代器_PHP教程

WBOY
WBOYOriginal
2016-07-12 09:04:391146browse

php迭代器,php代器

implements Iterator , 实现Iterator 的 current(); next(); key(); valid(); rewind();

 1 php
 2 /*
 3  *先定义一个数组
 4  *定义第一个位置 $position = 0
 5  *然后返回key 和value,
 6  *指向下一个位置 ++$position
 7  */  
 8 class myIterator implements Iterator{
 9         //先定义一个位置
10         private $position  = 0;
11         private $array;
12 
13         public function __construct(array $array){
14             $this->array = $array;
15         }
16         /**
17          * 倒带第一个元素的迭代器
18          * @return void 任何返回值将被忽略.
19          */
20         public function rewind(){
21             var_dump(__METHOD__);
22             $this->position = 0;
23         }
24         /**
25          * 检查当前位置是有效的
26          * @return boolean 返回值将bool型布尔,然后评估
27          */
28         public function valid(){
29             var_dump(__METHOD__);
30             //判断数组第一个元素是否存在
31             return isset($this->array[$this->position]);
32         }
33         /**
34          * 返回当前元素
35          * @return mixed 可以返回任何类型。
36          */
37         public function current(){
38             var_dump(__METHOD__);
39             //返回数组的第一个元素
40             return $this->array[$this->position];
41         }
42         /**
43          * 返回当前元素的关键
44          * @return mixed 标量成功,或null失败
45          */
46         public function key(){
47             var_dump(__METHOD__);
48             //返回数组第一个元素的key
49             return $this->position;
50         }
51         /**
52          * 前进到下一个元素
53          * @return void 任何返回值将被忽略。
54          */
55         public function next(){
56             var_dump(__METHOD__);
57             ++ $this->position;
58         }
59     }
60 
61 $array=[
62         "firstelement",
63         "secondeleent",
64         "lastelement"
65     ];
66 
67 $it = new myIterator($array);
68 foreach ($it as $key=>$value) {
69     echo $key.' => '.$value;
70     echo "
"; 71 }

 

执行结果:

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1072323.htmlTechArticlephp迭代器,php代器 implements Iterator , 实现Iterator 的current();next(); key(); valid();rewind(); 1 ? php 2 /* 3 *先定义一个数组 4 *定义第一个位置 $position...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn