• 展开微博窗口
  • QQ:52619941
  • 微信:cnmemory
  • 展开分类目录
  • 还没有账号?

Memory

使用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模拟一个迭代器》

评论

  1. leslie #1

    怎么像这样插入一段代码 博主能告知下么

    回复
    2017-02-20
  2. Memory #2

    :roll:

    回复
    2016-11-18
  3. Memory #3

    :roll:

    回复
    2016-11-18
  4.   #4

    666

    回复
    2016-10-12
  5. 游客 #5

    看起来掉包了啊

    回复
    2016-07-20
  6. Loshiu #6

    居然更新啦

    回复
    2016-07-20