PHP中的Iterator迭代對(duì)象屬性詳解
前言
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)文章
你應(yīng)該知道的PHP+MySQL分頁那點(diǎn)事
你應(yīng)該知道的PHP+MySQL分頁那點(diǎn)事,這篇文章主要為大家詳細(xì)介紹了PHP+MySQL分頁技術(shù),為大家提供了完整php分頁實(shí)例,感興趣的小伙伴們可以參考一下2016-08-08
PHP實(shí)現(xiàn)時(shí)間軸函數(shù)代碼
我們?cè)谡搲l(fā)帖、發(fā)表評(píng)論、或者是使用QQ空間發(fā)布日志、微博發(fā)表言論時(shí),會(huì)看到發(fā)表的內(nèi)容后的時(shí)間顯示為“剛剛”、“5分鐘前”、“昨天10:23”等,而不是直接顯示具體日期和時(shí)間2011-10-10
php function用法如何遞歸及return和echo區(qū)別
這篇文章主要介紹了php function用法如何遞歸及return和echo區(qū)別,需要的朋友可以參考下2014-03-03
非常不錯(cuò)的MySQL優(yōu)化的8條經(jīng)驗(yàn)
php開發(fā)中,一定要考慮mysql的執(zhí)行效率,下面的文章,可以很好的盡量避免的一些問題,學(xué)習(xí)php人要掌握這也是高手與菜鳥的區(qū)別,不是能做出來就叫高手的2008-03-03
php 采集書并合成txt格式的實(shí)現(xiàn)代碼
記得上次有過一個(gè)叫采集后的處理這個(gè)就是它的升級(jí)版本 連采再處理,合成一本書txt的。2009-03-03

