php中对object对象使用foreach循环操作

抛出疑问

php的对象是可以使用诸如foreach进行循环的。对象的循环,其实就是对像的开放属性进行的循环。但是在某些框架中,比如laravel中的对象循环,我们发现它并不是对属性进行遍历。

  • 普通对象:
class abc{
    public $a = 'a';
    public $b = 'b';
    protected $c = 'c';
    private $d = 'd';

    public function index(){
        return 'func';
    }
}
$abc = new abc();
foreach($abc as $item){
    dump($item);
}

打印结果如下:

"a"
"b"
  • laravel集合:
    这是使用laravel查询的分页对象
$list = Article::paginate(15);
IlluminatePaginationLengthAwarePaginator {#504 ▼
  #total: 2
  #lastPage: 1
  #items: IlluminateDatabaseEloquentCollection {#510 ▼
    #items: array:2 [▼
      0 => AppModelsArticle {#505 ▶}
      1 => AppModelsArticle {#497 ▶}
    ]
  }
  #perPage: 15
  #currentPage: 1
  #path: "http://hxsen.houxin.com/category/2"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}

提示
# 表示保护属性
+ 表示公开属性
- 表示私有属性

但是,对该循环的结果分析发现,它遍历的并不该对象本身。而是私有的#items属性下面的集合。

问题探究

查阅文档,我们发现最早php5.0的时候就已经支持了一个叫Iterator接口,并提供了一系列的方法供实现该接口的类定义。

interface Iterator extends Traversable {
    
    public function current();
   
    public function next();
    
    public function key();
    
    public function valid();
   
    public function rewind();
}

说明:
current:返回当前元素
next:向前移动到下一个元素
key: 返回当前元素的键
valid:检查当前位置是否有效
rewind:将迭代器倒回到第一个元素

问题解决

现在修改一下类,实现Iterator方法

class xyz implements Iterator{

    private $_items = array(1,2,3,4,5,6,7);

    public $a = 'a';
    public $b = 'b';
    protected $c = 'c';
    private $d = 'd';

    public function index(){
        return 'func';
    }

    // Rewind the Iterator to the first element
    public function rewind() { reset($this->_items); }
    // Return the current element
    public function current() { return current($this->_items); }
    // Return the key of the current element
    public function key() { return key($this->_items); }
    // Move forward to next element
    public function next() { return next($this->_items); }
    // Checks if current position is valid
    public function valid() { return ( $this->current() !== false ); }
}

上面的类中的_items 是我们自定义的数组集合。
此时,我们再次对它进行循环

$xyz = new xyz();
foreach($xyz as $value){
    dump($value);
}

现在,打印的结果变成了我们的那个_items数组的元素了。同时,内部的公开属性,也不在循环之列了。

1
2
3
4
5
6
7

总结说明

PHP中Interator接口的作用,就是允许对象以自己的方式迭代内部的数据,从而使它可以被循环访问
当循环执行valid返回false时,循环就结束了。

原文地址:https://www.cnblogs.com/hxsen/p/12704049.html