前言
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ì)腳本之家的支持。
您可能感興趣的文章:- PHP之預(yù)定義接口詳解
- PHP中預(yù)定義的6種接口介紹
- PHP聚合式迭代器接口IteratorAggregate用法分析
- PHP迭代器接口Iterator用法分析
- PHP設(shè)計(jì)模式之迭代器模式Iterator實(shí)例分析【對(duì)象行為型】
- PHP設(shè)計(jì)模式之迭代器(Iterator)模式入門與應(yīng)用詳解
- PHP使用DirectoryIterator顯示下拉文件列表的方法
- php中通過DirectoryIterator刪除整個(gè)目錄的方法
- PHP預(yù)定義接口——Iterator用法示例