6.4. 迭代对象的属性

未匹配的标注

持之以恒,方得始终!

foreach 取出对象的属性

实现迭代对象的属性

class myClass {
    public $a = 5;
    public $b = 7;
    public $c = 9;
}

$x = new myClass;
foreach ($x as $attr) {
    echo $attr . PHP_EOL;
}

更复杂的迭代器 iterator

class ObjectIterator implements Iterator {
    private $obj;
    private $count;
    private $currentIndex;

    function __construct($obj) {
        $this->obj = $obj;
        $this->count = count($this->obj->data);
    }

    // 将内部数据指针设置回数据开始处
    function rewind() {
        $this->currentIndex = 0;
    }

    // 将判断数据指针的当前位置是否还存在更多数据
    function valid() {
        return $this->currentIndex < $this->count;
    }

    // 将返回数据指针的值
    function key() {
        return $this->currentIndex;
    }

    // 将返回保存在当前数据指针的值
    function current() {
        return $this->obj->data[$this->currentIndex];
    }

    // 在数据中移动数据指针的位置
    function next() {
        $this->currentIndex++;
    }
}

class MyObject implements IteratorAggregate {
    public $data = [];

    function __construct($in) {
        $this->data = $in;
    }

    function getIterator() {
        return new ObjectIterator($this);
    }
}

$myObject = new MyObject([2, 4, 6, 8, 10]);

$myIterator = $myObject->getIterator();

for ($myIterator->rewind(); $myIterator->valid(); $myIterator->next()) {
    $key = $myIterator->key();
    $value = $myIterator->current();
    echo "$key => $value \n";
}

如有任何侵权行为,请通知我删除,谢谢大家!
个人邮箱:865460609@qq.com

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
Junwind
讨论数量: 0
发起讨论 只看当前版本


暂无话题~