温馨提示×

php如何遍历对象

养鱼的猫咪
468
2021-03-21 10:06:14
栏目: 编程语言

php如何遍历对象

在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";

}

0