{site_name}

{site_name}

🌜 搜索

在 PHP 中,使用对象迭代可以遍历对象的属性和方法

php 𝄐 0
php object,php obj,php object转 string,php ob_get_contents,php ob_end_clean 和ob_clean,php object转数组
在 PHP 中,使用对象迭代可以遍历对象的属性和方法。为了使一个对象具备迭代功能,需要实现Iterator接口或使用IteratorAggregate接口。

1. 使用Iterator接口:

php
class MyIterator implements Iterator {
private $position = 0;
private $data = array('apple', 'banana', 'cherry');

public function __construct() {
$this->position = 0;
}

public function rewind() {
$this->position = 0;
}

public function current() {
return $this->data[$this->position];
}

public function key() {
return $this->position;
}

public function next() {
$this->position++;
}

public function valid() {
return isset($this->data[$this->position]);
}
}

$iterator = new MyIterator();

foreach ($iterator as $key => $value) {
echo $key . ': ' . $value . "\n";
}


输出:

0: apple
1: banana
2: cherry


2. 使用IteratorAggregate接口:

php
class MyCollection implements IteratorAggregate {
private $items = array();

public function __construct() {
$this->items = array('apple', 'banana', 'cherry');
}

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

$collection = new MyCollection();

foreach ($collection as $key => $value) {
echo $key . ': ' . $value . "\n";
}


输出:

0: apple
1: banana
2: cherry


使用这两种方式之一,你可以自定义对象如何进行迭代,从而灵活地遍历对象的数据。