欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

PHP的面向?qū)ο笠嫣峁┝艘粋€(gè)非常聰明的特性,就是,可以使用foreach()方法通過(guò)循環(huán)方式取出一個(gè)對(duì)象的所有屬性,就像數(shù)組方式一樣,代碼如下:

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

如果需要實(shí)現(xiàn)更加復(fù)雜的行為,可以通過(guò)一個(gè)iterator(迭代器)來(lái)實(shí)現(xiàn)

//迭代器接口
interface MyIterator{
  //函數(shù)將內(nèi)部指針設(shè)置回?cái)?shù)據(jù)開(kāi)始處
  function rewind();
  //函數(shù)將判斷數(shù)據(jù)指針的當(dāng)前位置是否還存在更多數(shù)據(jù)
  function valid();
  //函數(shù)將返回?cái)?shù)據(jù)指針的值
  function key();
  //函數(shù)將返回將返回當(dāng)前數(shù)據(jù)指針的值
  function value();
  //函數(shù)在數(shù)據(jù)中移動(dòng)數(shù)據(jù)指針的位置
  function next();
}
//迭代器類(lèi)
class ObjectIterator implements MyIterator{
  private $obj;//對(duì)象
  private $count;//數(shù)據(jù)元素的數(shù)量
  private $current;//當(dāng)前指針
  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
*/

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語(yǔ)法入門(mén)教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總

希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論