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

PHP中的Iterator迭代對(duì)象屬性詳解

 更新時(shí)間:2019年04月12日 08:32:12   作者:itbsl  
這篇文章主要給大家介紹了關(guān)于PHP中Iterator迭代對(duì)象屬性的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用PHP具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

前言

foreach用法和之前的數(shù)組遍歷是一樣的,只不過這里遍歷的key是屬性名,value是屬性值。在類外部遍歷時(shí),只能遍歷到public屬性的,因?yàn)槠渌亩际鞘鼙Wo(hù)的,類外部不可見。

class HardDiskDrive {

  public $brand;
  public $color;
  public $cpu;
  public $workState;

  protected $memory;
  protected $hardDisk;

  private $price;

  public function __construct($brand, $color, $cpu, $workState, $memory, $hardDisk, $price) {

    $this->brand = $brand;
    $this->color = $color;
    $this->cpu  = $cpu;
    $this->workState = $workState;
    $this->memory = $memory;
    $this->hardDisk = $hardDisk;
    $this->price = $price;
  }

}

$hardDiskDrive = new HardDiskDrive('希捷', 'silver', 'tencent', 'well', '1T', 'hard', '$456');

foreach ($hardDiskDrive as $property => $value) {

  var_dump($property, $value);
  echo '<br>';
}

輸出結(jié)果為:

string(5) "brand" string(6) "希捷"
string(5) "color" string(6) "silver"
string(3) "cpu" string(7) "tencent"
string(9) "workState" string(4) "well"

通過輸出結(jié)果我們也可以看得出來常規(guī)遍歷是無法訪問受保護(hù)的屬性的。

如果我們想遍歷出對(duì)象的所有屬性,就需要控制foreach的行為,就需要給類對(duì)象,提供更多的功能,需要繼承自Iterator的接口:

該接口,實(shí)現(xiàn)了foreach需要的每個(gè)操作。foreach的執(zhí)行流程如下圖:

看圖例中,foreach中有幾個(gè)關(guān)鍵步驟:5個(gè)。

而Iterator迭代器中所要求的實(shí)現(xiàn)的5個(gè)方法,就是用來幫助foreach,實(shí)現(xiàn)在遍歷對(duì)象時(shí)的5個(gè)關(guān)鍵步驟:

當(dāng)foreach去遍歷對(duì)象時(shí), 如果發(fā)現(xiàn)對(duì)象實(shí)現(xiàn)了Ierator接口, 則執(zhí)行以上5個(gè)步驟時(shí), 不是foreach的默認(rèn)行為, 而是調(diào)用對(duì)象的對(duì)應(yīng)方法即可:

示例代碼:

class Team implements Iterator {

  //private $name = 'itbsl';
  //private $age = 25;
  //private $hobby = 'fishing';

  private $info = ['itbsl', 25, 'fishing'];

  public function rewind()
  {
    reset($this->info); //重置數(shù)組指針
  }

  public function valid()
  {
    //如果為null,表示沒有元素,返回false
    //如果不為null,返回true

    return !is_null(key($this->info));
  }

  public function current()
  {
    return current($this->info);
  }

  public function key()
  {
    return key($this->info);
  }

  public function next()
  {
    return next($this->info);
  }

}

$team = new Team();

foreach ($team as $property => $value) {

  var_dump($property, $value);
  echo '<br>';
}

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論