PHP 提供了一種定義對(duì)象的方法使其可以通過單元列表來遍歷,例如用 foreach 語句。默認(rèn)情況下,所有可見屬性都將被用于遍歷。
示例 #1 簡(jiǎn)單的對(duì)象遍歷
<?php
class MyClass
{
public $var1 = 'value 1';
public $var2 = 'value 2';
public $var3 = 'value 3';
protected $protected = 'protected var';
private $private = 'private var';
function iterateVisible() {
echo "MyClass::iterateVisible:\n";
foreach ($this as $key => $value) {
print "$key => $value\n";
}
}
}
$class = new MyClass();
foreach($class as $key => $value) {
print "$key => $value\n";
}
echo "\n";
$class->iterateVisible();
?>
以上例程會(huì)輸出:
var1 => value 1 var2 => value 2 var3 => value 3 MyClass::iterateVisible: var1 => value 1 var2 => value 2 var3 => value 3 protected => protected var private => private var