我有類實現了Countable,ArrayAccess,Iterator和Serializable。 我有一個公共varibale $數據,數組形式。而我的迭代implementions:Arrayaccess,迭代器和當前()
public function rewind() { return reset($this->data); }
public function current() { return current($this->data); }
public function key() { return key($this->data); }
public function next() { return next($this->data); }
public function valid() { return isset($this->data[$this->key()]); }
好一切工作與foreach循環,但如果我手動調用current($arrayObject)
,它返回整個$data
陣列,它不是德電流。我可以做current($arrayObject->data)
,但是我想盡可能保持原生數組的功能。
這是php的行爲吧? (不是我的代碼錯誤)是否有任何解決方法,沒有自定義功能(手指交叉)?
[編輯]滿級的簡化版本(工作):
$arrayObject = mysqli_fetch_object($this->result_id, "simpleMysqliResult ", array(array(
"fields" => array("field1", "field2", "field3")
)));
class simpleMysqliResult implements Countable, ArrayAccess, Iterator, Serializable {
public $data = array();
public function __construct($input) {
extract($input);
foreach ($fields as $field) {
$this->data[$field] = $this->{$field};
unset($this->{$field});
}
}
public function &toArray() { return $this->data; }
public function offsetGet($index) { return $this->data[$index]; }
public function offsetSet($index, $value) { $this->data[$index] = $value; }
public function offsetUnset($index) { unset($this->data[$index]); }
public function offsetExists($index) { return $this->offsetGet($index) !== null; }
public function count() { return count($this->data); }
public function rewind() { return reset($this->data); }
public function current() { return current($this->data); }
public function key() { return key($this->data); }
public function next() { return next($this->data); }
public function valid() { return isset($this->data[$this->key()]); }
public function serialize() { return serialize($this->data); }
public function unserialize($str) { return $this->data = unserialize($str); }
public function __call($func, $argv) {
if (!is_callable($func) || substr($func, 0, 6) !== 'array_')
{
throw new BadMethodCallException(__CLASS__.'->'.$func);
}
return call_user_func_array($func, array_merge(array($this->data), $argv));
}
}
顯示全班。我見過類似的實現,這很好。 – KingCrunch 2012-01-10 12:30:12
添加,簡化了一下,另外,我擴展了這個類,但是隻覆蓋了Arrayacces的實現 – Kristian 2012-01-10 12:41:46
你有沒有想過擴展[ArrayObject](http://php.net/arrayobject)?它提供了許多你需要的功能。 – cmbuckley 2012-01-10 12:43:22