PHP Conference Japan 2024

IteratorAggregate 介面

(PHP 5, PHP 7, PHP 8)

簡介

用於建立外部迭代器的介面。

介面概要

interface IteratorAggregate extends Traversable {
/* 方法 */
}

範例

範例 #1 基本用法

<?php

class myData implements IteratorAggregate
{
public
$property1 = "第一個公開屬性";
public
$property2 = "第二個公開屬性";
public
$property3 = "第三個公開屬性";
public
$property4 = "";

public function
__construct()
{
$this->property4 = "最後一個屬性";
}

public function
getIterator(): Traversable
{
return new
ArrayIterator($this);
}
}

$obj = new myData();

foreach (
$obj as $key => $value) {
var_dump($key, $value);
echo
"\n";
}

?>

上述範例將會輸出類似以下的內容:

string(9) "property1"
string(19) "Public property one"

string(9) "property2"
string(19) "Public property two"

string(9) "property3"
string(21) "Public property three"

string(9) "property4"
string(13) "last property"

目錄

新增註記

使用者貢獻的註記 4 則註記

trumbull dot j at gmail dot com
7 年前
這可能看起來很明顯,但您可以從 IteratorAggregate::getIterator() 的實作中返回一個已編譯的產生器。

<?php
class Collection implements IteratorAggregate
{
private
$items = [];

public function
__construct($items = [])
{
$this->items = $items;
}

public function
getIterator()
{
return (function () {
while(list(
$key, $val) = each($this->items)) {
yield
$key => $val;
}
})();
}
}

$data = [ 'A', 'B', 'C', 'D' ];
$collection = new Collection($data);

foreach (
$collection as $key => $val) {
echo
sprintf("[%s] => %s\n", $key, $val);
}
?>
Tab Atkins
12 年前
請注意,至少在 5.3 版本,`getIterator()` 仍然不允許返回一般的陣列。

在某些地方,文件會將陣列包裝成 `ArrayObject` 並返回它。**不要這樣做。** `ArrayObject` 在迭代時會忽略任何空字串鍵值(同樣,至少在 5.3 版本是如此)。

請改用 `ArrayIterator`。如果它沒有自己的一堆奇妙的錯誤,我不會感到驚訝,但至少當你用這個方法使用它時,它可以正常工作。
Martin Speer
5 年前
你可以在新的 PHP 7 版本中的 `getIterator` 中使用 `yield from`。

<?php

class Example implements \IteratorAggregate
{
protected
$data = [];

public function
__construct(array $data)
{
$this->data = $data;
}

public function
getIterator()
{
yield from
$this->data;
}
}

$test = new Example([1, 2, 3]);

foreach (
$test as $node) {
echo
$test, PHP_EOL;
}

/*
* 輸出:
*
* 1
* 2
* 3
*/
?>
Lubaev.K
11 年前
<?php
// 迭代器聚合
// 建立索引式和關聯式陣列。

class myData implements IteratorAggregate {

private
$array = [];
const
TYPE_INDEXED = 1;
const
TYPE_ASSOCIATIVE = 2;

public function
__construct( array $data, $type = self::TYPE_INDEXED ) {
reset($data);
while( list(
$k, $v) = each($data) ) {
$type == self::TYPE_INDEXED ?
$this->array[] = $v :
$this->array[$k] = $v;
}
}

public function
getIterator() {
return new
ArrayIterator($this->array);
}

}

$obj = new myData(['one'=>'php','javascript','three'=>'c#','java',], /*類型 1 或 2*/ );

foreach(
$obj as $key => $value) {
var_dump($key, $value);
echo
PHP_EOL;
}

// 如果 類型 == 1
#int(0)
#string(3) "php"
#int(1)
#string(10) "javascript"
#int(2)
#string(2) "c#"
#int(3)
#string(4) "java"

// 如果 類型 == 2
#string(3) "one"
#string(3) "php"
#int(0)
#string(10) "javascript"
#string(5) "three"
#string(2) "c#"
#int(1)
#string(4) "java"
?>

祝你好運!
To Top