類與物件(PHP5)之八:物件叠代(Object Iteration)

日期:2006-09-26  作者:喜騰小二  來源:PHPChina


PHP5提供一個為物件定義透過一連串的訊息被重述的途徑成為可能,例如使用一個foreach陳述式。預設地,所有可見的內容將用來叠代(反覆)。
例子
19-20. 簡單的物件叠代(Simple Object Iteration)
PHP程式碼如下:

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:
"
;
       foreach(
$this as $key => $value){  print "$key => $value
"
;  }
    }
}
$class = new MyClass();
foreach(
$class as $key => $value){   print "$key => $value
"
;  }
echo 
"
"
;
$class->iterateVisible();
?> 


如輸出顯示,foreach重述能透過全部可見變數被訪問。更進一步,妳可以實現一個PHP5的指定的內在介麵叠代器(Iterator)。允許物件描述什麼是物件重述和物件如何被重述的。
例子
19-21. 叠代器實現物件叠代(Object Iteration implementing Iterator)
PHP程式碼如下:

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


上例將輸出:

CODE:
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
key: 2
2:
3
next:
current:
valid:

在定義類時妳也可以不必透過簡單實現PHP5的IteratorAggregate介麵定義所有的叠代器函式。
例19-22.IteratorAggregate物件叠代實現
PHP程式碼如下:

php
class MyCollection implements IteratorAggregate
{   private $items = array();
    
private $count 0;
    
// Required definition of interface IteratorAggregate
    
public function getIterator() 
    {    return new 
MyIterator($this->items);
    }
     
public function add($value
    {    
        
$this->items[$this->count++] = $value;
    }
}
$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]

"
;  }
?> 


上例將輸出:

[Copy to clipboard]CODE:
rewinding
current: value 1
valid:
1
current: value 1
key: 0
key/value: [0 -> value 1]
next: value
2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1
-> value 2]
next: value 3
current: value 3
valid: 1
current:
value 3
key: 2
key/value: [2 -> value
3]
next:
current:
valid:

<<<返回技術中心

技術文章

站內新聞

我要啦免费统计