PHP 5 提供了一种定义对象的方法使其可以通过单元列表来遍历,例如用 foreach 语句。默认情况下,所有可见属性都将被用于遍历。
Example #1 简单的对象遍历
class MyClass { public $var1 = 1; public $var2 = 2; public $var3 = 3; protected $protected = 'protected var'; private $private = 'private var'; function iterateVisible(){ echo "MyClass::iterateVisible: "; foreach($this as $key => $value){ print "$key=>$value "; } } } $class = new MyClass(); foreach($class as $key => $value){ print "$key => $value "; } echo " "; $class->iterateVisible();
输出结果:
var1 => 1
var2 => 2
var3 => 3
MyClass::iterateVisible:
var1=>1
var2=>2
var3=>3
protected=>protected var
private=>private var
如上所示,foreach 遍历了所有其能够访问的可见属性。
更进一步,可以实现 Iterator接口。可以让对象自行决定如何遍历以及每次遍历时那些值可用。
class MyIterator implements Iterator{ private $var = array(); public function __construct($array) { if(is_array($array)){ $this->var = $array; } } public function rewind(){ echo "rewinding "; reset($this->var); } public function current(){ $var = current($this->var); echo "current:$var "; return $var; } public function key(){ $var = key($this->var); echo "key:$var "; return $var; } public function next(){ $var = next($this->var); echo "next:$var "; return $var; } public function valid(){ $var = $this->current()!==false; echo "valid:$var "; return $var; } } $values = array(1,2,3); $it = new MyIterator($values); foreach($it as $a => $b){ print "$a:$b "; }
输出结果:
rewinding
current:1
valid:1
current:1
key:0
0:1
next:2
current:2
valid:1
current:2
key:1
1:2
next:3
current:3
valid:1
current:3
key:2
2:3
next:
current:
valid:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理