|
对象遍历:foreach,遍历对象的公有属性(将公有属性的值和属性名赋值给对应$value和$key)
遍历某一个属性的数组,实现Iterator接口
接口iterator:类实现Iterator接口
current:获取当前数组元素的值$this->hobby[$this->position]
key:获取当前下标
next:数组指针下移
rewind:重置指针
valid:判断当前指针是否有效,使用key函数判断数组下标
<?php
//预定义接口
class Person implements Iterator{
//属性
private $point = 0;
protected $hobby = array('b' => '篮球','足球','台球','羽毛球');
protected $school = array('北京','上海','广州','武汉','郑州','成都');
//实现接口里的方法
//获取当前数组元素当前指针位置的元素值
public function current(){
return $this->hobby[$this->point];
}
//获取当前数组元素当前指针的位置(数组下标)
public function key(){
return $this->point;
}
//数组的指针下移
public function next(){
$this->point++;
}
//重置数组指针
public function rewind(){
$this->point = 0;
}
//判断数组的指针是否有效
public function valid(){
//判断当前指针所指向的位置是否有值即可
if(isset($this->hobby[$this->point])) return true;
return false;
}
}
//实例化对象
$person = new Person();
//遍历
foreach($person as $key => $value){
echo $key . ':' . $value . '<br/>';
}
|
|
|