This article to share the content is about "PHP class and object" traversal, has a certain reference value, the need for friends can refer to
Traversing objects
PHP 5 provides a way to define objects so that they can traverse through a list of cells
By default, all visible properties are used for traversal.
Example #1 Simple Object Traversal (a foreach traversal of all the visible properties it can access.) ) <?phpclass myclass{public $var 1 = ' value 1 '; Public $var 2 = ' value 2 '; Public $var 3 = ' value 3 '; Protected $protected = ' protected var '; Private $private = ' private var '; function iteratevisible () { echo "myclass::iteratevisible:\n"; foreach ($this as $key + $value) { print "$key = = $value \ n";}} $class = new MyClass (), foreach ($class as $key = = $value) { print "$key = + $value \ n";} echo "\ n"; $class->iteratevisible ();? >
Implements the Iterator interface (pre-defined interface). You can let the object decide for itself how to traverse and which values are available each time.
#接口摘要 #iterator extends traversable {Abstract public mixed current (void)// Returns the element that the current index cursor points to abstract public scalar key (void)//Returns the key that the current index cursor points to, abstract public void next (void)//move Current index Tour Mark to next element abstract public void rewind (void)//Reset index cursor Abstract public boolean valid (void)//Determine whether the element pointed to by the current index cursor is valid These methods are automatically called when an object that implements the iterator interface is traversed by a foreach. The invocation is in the following sequence: Rewind (), valid (), current (), key (), Next ()
example #2 implements object traversal of Iterator interface <?phpclass Myiterator implements iterator{private $var = arr Ay (); Public function __construct ($array) {if (Is_array ($array)) {$this->var = $array; }} Public Function rewind () {echo "rewinding\n"; Reset ($this->var); The public Function current () {$var = current ($this->var); echo "Current: $var \ n"; return $var; Public Function key () {$var = key ($this->var); echo "key: $var \ n"; return $var; Public function Next () {$var = next ($this->var); echo "Next: $var \ n"; return $var; Public Function Valid () {$var = $this->current ()!== false; echo "valid: {$var}\n"; return $var; }} $values = array, $it = new Myiterator ($values), foreach ($it as $a + = $b) {print "$a: $b \ n";}?