亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

PHP迭代器和迭代的實現(xiàn)與使用方法分析

 更新時間:2018年04月19日 14:17:20   作者:LSGOZJ  
這篇文章主要介紹了PHP迭代器和迭代的實現(xiàn)與使用方法,結合實例形式分析了PHP迭代器的概念、原理、定義與使用方法,需要的朋友可以參考下

本文實例講述了PHP迭代器和迭代的實現(xiàn)與使用方法。分享給大家供大家參考,具體如下:

PHP的面向對象引擎提供了一個非常聰明的特性,就是,可以使用foreach()方法通過循環(huán)方式取出一個對象的所有屬性,就像數(shù)組方式一樣,代碼如下:

class Myclass{
  public $a = 'php';
  public $b = 'onethink';
  public $c = 'thinkphp';
}
$myclass = new Myclass();
//用foreach()將對象的屬性循環(huán)出來
foreach($myclass as $key.'=>'.$val){
  echo '$'.$key.' = '.$val."<br/>";
}
/*返回
  $a = php
  $b = onethink
  $c = thinkphp
*/

如果需要實現(xiàn)更加復雜的行為,可以通過一個iterator(迭代器)來實現(xiàn)

//迭代器接口
interface MyIterator{
  //函數(shù)將內(nèi)部指針設置回數(shù)據(jù)開始處
  function rewind();
  //函數(shù)將判斷數(shù)據(jù)指針的當前位置是否還存在更多數(shù)據(jù)
  function valid();
  //函數(shù)將返回數(shù)據(jù)指針的值
  function key();
  //函數(shù)將返回將返回當前數(shù)據(jù)指針的值
  function value();
  //函數(shù)在數(shù)據(jù)中移動數(shù)據(jù)指針的位置
  function next();
}
//迭代器類
class ObjectIterator implements MyIterator{
  private $obj;//對象
  private $count;//數(shù)據(jù)元素的數(shù)量
  private $current;//當前指針
  function __construct($obj){
    $this->obj = $obj;
    $this->count = count($this->obj->data);
  }
  function rewind(){
    $this->current = 0;
  }
  function valid(){
    return $this->current < $this->count;
  }
  function key(){
    return $this->current;
  }
  function value(){
    return $this->obj->data[$this->current];
  }
  function next(){
    $this->current++;
  }
}
interface MyAggregate{
  //獲取迭代器
  function getIterator();
}
class MyObject implements MyAggregate{
  public $data = array();
  function __construct($in){
    $this->data = $in;
  }
  function getIterator(){
    return new ObjectIterator($this);
  }
}
//迭代器的用法
$arr = array(2,4,6,8,10);
$myobject = new MyObject($arr);
$myiterator = $myobject->getIterator();
for($myiterator->rewind();$myiterator->valid();$myiterator->next()){
  $key = $myiterator->key();
  $value = $myiterator->value();
  echo $key.'=>'.$value;
  echo "<br/>";
}
/*返回
  0=>2
  1=>4
  2=>6
  3=>8
  4=>10
*/

更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家PHP程序設計有所幫助。

相關文章

最新評論