在php中實現遍歷對象的方法
1.使用foreach語句遍歷對象
class bee{
public $a = 1;
protected $b = 2;
private $c = 3;
}
$obj = new bee();
foreach($obj as $key => $val){
echo $key.'-'.$val;
}
2.使用Iterator接口遍歷對象
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a: $b\n";
}
3.使用IteratorAggregate遍歷對象
$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');
foreach ($coll as $key => $val) {
echo "key/value: [$key -> $val]\n\n";
}