PHP 使对象可以像数组一样进行foreach循环,要求属性必须是私有

答案

PHP5开始支持了接口, 并且内置了Iterator接口, 所以如果你定义了一个类,并实现了Iterator接口,那么你的这个类对象就是ZEND_ITER_OBJECT,否则就是ZEND_ITER_PLAIN_OBJECT

对于ZEND_ITER_PLAIN_OBJECT的类,foreach会通过HASH_OF获取该对象的默认属性数组,然后对该数组进行foreach。而对于ZEND_ITER_OBJECT的类对象,则会通过调用对象实现的Iterator接口相关函数来进行foreach

  1. class sample implements Iterator
  2. {
  3. private $_items = array(1,2,3,4,5,6,7);
  4. public function __construct() {
  5. ;//void
  6. }
  7. public function rewind() { reset($this->_items); }
  8. public function current() { return current($this->_items); }
  9. public function key() { return key($this->_items); }
  10. public function next() { return next($this->_items); }
  11. public function valid() { return ( $this->current() !== false ); }
  12. }

测试代码:

  1. $sa = new sample();
  2. foreach($sa as $key => $val){
  3. print $key . "=>" .$val;
  4. }

参考资料