溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

php中Iterator迭代對象屬性的使用方法

發(fā)布時(shí)間:2020-10-10 17:28:34 來源:億速云 閱讀:101 作者:小新 欄目:編程語言

小編給大家分享一下php中Iterator迭代對象屬性的使用方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

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ù)的屬性的。
如果我們想遍歷出對象的所有屬性,就需要控制foreach的行為,就需要給類對象,提供更多的功能,需要繼承自Iterator的接口:
該接口,實(shí)現(xiàn)了foreach需要的每個(gè)操作。foreach的執(zhí)行流程如下圖:

php中Iterator迭代對象屬性的使用方法

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

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

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

php中Iterator迭代對象屬性的使用方法

示例代碼:

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>';
}

以上是php中Iterator迭代對象屬性的使用方法的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI