PHP 生成器類
簡介
使用迴圈結構(例如 **foreach**)遍歷大型資料集合需要大量的記憶體和相當的處理時間。使用 **生成器**,可以迭代資料集而無需這些開銷。生成器函式類似於普通函式。但是,生成器不使用函式中的 return 語句,而是使用 **yield** 關鍵字重複執行,以便提供要迭代的值。
yield 關鍵字是生成器機制的核心。儘管它的用法看起來類似於 return,但它不會停止函式的執行。它提供下一個要迭代的值並暫停函式的執行。
語法
Generator implements Iterator {
/* Methods */
public current ( void ) : mixed
public getReturn ( void ) : mixed
public key ( void ) : mixed
public next ( void ) : void
public rewind ( void ) : void
public send ( mixed $value ) : mixed
public throw ( Throwable $exception ) : mixed
public valid ( void ) : bool
public __wakeup ( void ) : void
}方法
public Generator::current ( void ) − mixed — 獲取產生的值
public Generator::getReturn ( void ) : mixed — 獲取生成器的返回值。
public Generator::key ( void ) − mixed — 獲取產生的值的鍵。
public Generator::next ( void ) − void — 恢復生成器的執行。與使用 NULL 作為引數呼叫 Generator::send() 的效果相同。
public Generator::rewind ( void ) − void — 倒回迭代器。如果迭代已經開始,這將丟擲異常。
public Generator::send ( mixed $value ) : mixed — 將給定值傳送到生成器作為當前 yield 表示式的結果,並恢復生成器。
public Generator::throw ( Throwable $exception ) − mixed — 將異常拋入生成器並恢復生成器的執行。
public Generator::valid ( void ) − bool — 檢查迭代器是否已關閉
public Generator::__wakeup ( void ) − void — 丟擲異常,因為生成器無法序列化。
Generator 類實現了 Iterator 介面。Generator 物件不能透過 new 例項化。任何包含 yield 關鍵字的使用者定義函式都會建立 Generator 類的物件。
生成器示例
由於生成器實現了 Iterator 介面,因此可以使用 foreach 迴圈遍歷產生的值。
<?php
function squaregenerator(){
for ($i=1; $i<=5; $i++){
yield $i*$i;
}
}
$gen=squaregenerator();
foreach ($gen as $val){
echo $val . " ";
}
?>輸出
以上程式顯示以下輸出
1 4 9 16 25
以下示例使用生成器類的 current() 和 next() 方法遍歷產生的值。使用 valid() 方法檢查迴圈條件。
示例
<?php
function squaregenerator(){
for ($i=1; $i<=5; $i++){
yield $i*$i;
}
}
$gen=squaregenerator();
while ( $gen->valid() ){
echo "key: " . $gen->key(). " value: ". $gen->current() . "
";
$gen->next();
}
?>輸出
以上程式顯示以下輸出
key: 0 value: 1 key: 1 value: 4 key: 2 value: 9 key: 3 value: 16 key: 4 value: 25
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP