Home > Article > Backend Development > [php classes and objects] traversal
The content shared with you in this article is about [php classes and objects] traversal, which has certain reference value. Friends in need can refer to it
Traversing objects
PHP 5 provides a way to define objects so that they can be traversed through a list of cells
By default, all visible properties will be used for traversal.
Example #1 简单的对象遍历(foreach 遍历所有其能够访问的可见属性。)<?phpclass MyClass{ public $var1 = 'value 1'; public $var2 = 'value 2'; public $var3 = '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 (predefined interface). You can let the object decide how to traverse and which values are available each time it is traversed.
#接口摘要#Iterator extends Traversable { abstract public mixed current ( void ) //返回当前索引游标指向的元素 abstract public scalar key ( void ) //返回当前索引游标指向的键 abstract public void next ( void ) //移动当前索引游标到下一元素 abstract public void rewind ( void ) //重置索引游标 abstract public boolean valid ( void ) //判断当前索引游标指向的元素是否有效 } 当一个实现了Iterator接口的对象,被foreach遍历时,会自动调用这些方法。 调用的循序是:rewind() -> valid() -> current() -> key() -> next()
Example #2 实现 Iterator 接口的对象遍历<?phpclass MyIterator implements Iterator{ private $var = array(); public function __construct($array) { if (is_array($array)) { $this->var = $array; } } public function rewind() { echo "rewinding\n"; reset($this->var); } 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(1,2,3);$it = new MyIterator($values);foreach ($it as $a => $b) { print "$a: $b\n"; }?>
Related recommendations:
[php classes and objects] Anonymous class
[php classes and objects] overloading
The above is the detailed content of [php classes and objects] traversal. For more information, please follow other related articles on the PHP Chinese website!