时间:2022-12-06 01:53
在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";
}