首頁  >  文章  >  後端開發  >  php遍歷對象

php遍歷對象

伊谢尔伦
伊谢尔伦原創
2016-11-23 14:01:151741瀏覽

PHP 5 提供了一種定義物件的方法使其可以透過單元列表來遍歷,例如用 foreach 語句。預設情況下,所有可見屬性都將用於遍歷。

Example #1 簡單的物件遍歷

class MyClass
{
    public $var1 = 1;
    public $var2 = 2;
    public $var3 = 3;
    protected $protected = 'protected var';
    private $private = 'private var';
    function iterateVisible(){
        echo "MyClass::iterateVisible:<br>";
        foreach($this as $key => $value){
            print "$key=>$value<br>";
        }
    }
} 
$class = new MyClass();
foreach($class as $key => $value){
    print "$key => $value<br>";
}
echo "<br>";
$class->iterateVisible();

輸出結果:

var1 => 1

var2 => 2

var3 => 3

var2 => 2

var3 => 3

2 => 2

var3 => 3

元> >2

var3=>3

protected=>protected var

private=>private var

如上所示,foreach 遍歷了所有其能夠存取的可見屬性。

更進一步,可以實現 Iterator介面。可以讓物件自行決定如何遍歷以及每次遍歷時那些值可用。

class MyIterator implements Iterator{
    private $var = array();
    public function __construct($array)
    {
        if(is_array($array)){
            $this->var = $array;
        }
    }
    public function rewind(){
        echo "rewinding<br>";
        reset($this->var);
    }
    public function current(){
        $var = current($this->var);
        echo "current:$var<br>";
        return $var;
    }
    public function key(){
        $var = key($this->var);
        echo "key:$var<br>";
        return $var;
    }
    public function next(){
        $var = next($this->var);
        echo "next:$var<br>";
        return $var;
    }
    public function valid(){
        $var = $this->current()!==false;
        echo "valid:$var<br>";
        return $var;
    }
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach($it as $a => $b){
    print "$a:$b<br>";
}

輸出結果:

rewinding

current:1

valid:1

current:1

key:0

0:1

next:2

current:2

valid:1

current:2

key:1

1:2

next:3

current:3

valid:1

current:3

current:

valid:

可以用 IteratorAggregate介面以取代實作所有的 Iterator 方法。 IteratorAggregate 只需要實作一個方法 IteratorAggregate::getIterator(),其應傳回一個實作了 Iterator 的類別的實例。

Example #3 透過實作IteratorAggregate 來遍歷物件

include_once(&#39;class2.php&#39;);
class MyCollection implements IteratorAggregate
{
    private $items = array();
    private $count = 0;
    public function getIterator(){
       return new MyIterator($this->items);
    }
    public function add($value){
        $this->items[$this->count++] = $value;
    }
}
$coll = new MyCollection();
$coll -> add(&#39;1&#39;);
$coll -> add(&#39;2&#39;);
$coll -> add(&#39;3&#39;);
foreach($coll as $k => $v){
    echo "key/value:[$k->$v]<br><br>";
}

輸出結果:

rewinding

current:1

valid:1

. 1]

 

next:2

current:2

valid:1

current:2

key:1

key/value-valp/value current:3

valid:1

current:3

key:2

key/value:[2->3]

:003:點
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn