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

<?php

class sample implements Iterator {

    private $_items = array (0, 1, 2, 3 );

 

    public function __construct() {

        ; //void

    }

    public function rewind() {

        reset ( $this->_items );

    }

    public function current() {

        return current ( $this->_items );

    }

    public function key() {

        return key ( $this->_items );

    }

    public function next() {

        return next ( $this->_items );

    }

    public function valid() {

        return ($this->current () !== false);

    }

}

 

$sa = new sample ();

foreach ( $sa as $key => $val ) {

    print $key . "=>" . $val . '<br/>';

}

/**

**输出结果为

0=>0

1=>1

2=>2

3=>3

**/

  http://www.laruence.com/2008/10/31/574.html

你可能感兴趣的:(foreach)