0bc07.php

来自「介绍PHP5的给类型函数应用」· PHP 代码 · 共 68 行

PHP
68
字号
<?php// Declare a new class that implements Iterator, that will allow for more// natural iteration over Arrays with key accessclass KeyArrayIterator implements Iterator {	// Declare a property to hold the actual data array	protected $data;		// Now make our constructor	public function __construct($v) {		// Just store this into our protected storage		$this->data = $v;	}		// Ok, we need to declare 'rewind' as part of the implementing Iterator	public function rewind() {		// Well the data is still an array, so use the array function:		return reset($this->data);	}		// To implement Iterator, declare 'next' which moves the pointer forward	public function next() {		// Again, since an array, just use the array function		return next($this->data);	}		// To implement Iterator, we need a 'valid', Whether the pointer is valid	public function valid() {		// Use the array 'current' function to check if we are at a valid		// point in the array or not.		return (current($this->data) === false) ? false : true;	}		// Now we also need 'key' that returns just a key for this entry.	public function key() {		// Just use the arrays build in 'key' function to do this		return key($this->data);	}		// Finally define 'current', the real meat of this object	public function current() {		// Current needs to return the current entry.  However we want		// this to really return an object that contains both value		// and key, therefore let's do just this:		return new KeyArrayItem(key($this->data), current($this->data));	}}// Now we need to define the KeyArrayItem class that we used in the// current function of our Iterator.class KeyArrayItem {	// First of all, declare properties to hold the data:	public $key;	public $value;		// Now make a constructor that will accept these two data points	public function __construct($k, $v) {		// Just save them		$this->key = $k;		$this->value = $v;	}		// Now as one last thing, define a __toString method that will return	// just the value portion if the object is accessed in a direct manner	public function __toString() {		return (string) $this->value;	}}?>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?