PHP — Foreach Object
in PHP with 0 comment, Views is 27

PHP — Foreach Object

in PHP with 0 comment, Views is 27

题目描述

使对象可以像数组一样进行 foreach 循环

要求属性必须是私有属性

代码实现

<?php

class Test implements Iterator
{
    /**
     * @var array
     */
    private $array;

    /**
     * 构造器
     * @param array $array 初始化数组
     */
    public function __construct($array = [])
    {
        $this -> array = $array;
    }

    /**
     * 重置指针
     */
    public function rewind()
    {
        reset($this -> array);
    }

    /**
     * 验证
     */
    public function valid()
    {
        return ($this -> current() !== false);
    }

    /**
     * 获取当前 value
     */
    public function current()
    {
        return current($this -> array);
    }

    /**
     * 获取当前 key
     */
    public function key()
    {
        return key($this -> array);
    }

    /**
     * 指针下移
     */
    public function next()
    {
        return next($this -> array);
    }
}

// 测试
$array = new Test(['one',
                   'two',
                   'three',
                   'my' => 'OceanicKang']);

foreach ($array as $k => $v) {
    echo $k . ' => ' . $v . "\n";
}

1.png

Responses
选择表情