使用PHP模拟一个迭代器
其实在PHP中,数组已经很方便使用了,模拟迭代器只是为了自己学习玩玩。
class Super {
protected $data;
public function __get($param) {
if (isset($this->$param)) {
return $this->$param;
}
}
public function __set($param, $val) {
if (isset($this->$param)) {
$this->$param = $val;
} else {
$this->data[$param] = $val;
}
}
}
class Player extends Super {
private $name = '';
private $sex = 0;
private $age = 0;
public function __construct($name, $sex, $age) {
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
public function getName() {
return $this->name;
}
}
class CustomIterator implements Iterator {
private $_key = -1;
private $_datas = array();
public function push(&$element) {
array_push($this->_datas, $element);
}
public function put($element) {
}
public function key() {
return $this->_key;
}
public function next() {
if ($this->hasNext()) {
$this->_key++;
}
return $this->current();
}
public function hasNext() {
return isset($this->_datas[$this->_key + 1]);
}
public function rewind() {
$this->_key = -1;
}
public function current() {
return $this->_datas[$this->_key];
}
public function valid() {}
}
class PlayerStorage extends CustomIterator {
public function get($index) {
return $this->_datas[$index];
}
}
$playerStorage = new PlayerStorage();
if ($playerStorage instanceOf Iterator) {
echo "It's a Iterator!";
}
$player1 = new Player("关于", 0, 18);
$player2 = new Player("张飞", 1, 29);
$playerStorage->push($player1);
$playerStorage->push($player2);
while($playerStorage->hasNext()) {
$player = $playerStorage->next();
echo $player->getName();
}
码字很辛苦,转载请注明来自雨林寒舍的《使用PHP模拟一个迭代器》
2016-07-19
编程语言
11
11
怎么像这样插入一段代码 博主能告知下么
666
看起来掉包了啊
居然更新啦