ID: 45684
Comment by: fqqdk at freemail dot hu
Reported By: puts dot email at gmail dot com
Status: Open
Bug Type: Feature/Change Request
Operating System: N/A
PHP Version: 5.3.0alpha1
New Comment:
I don't see why ArrayAccess can allow objects (or anything) as array
keys, and Iterator doesn't. This is inconsistent.
Previous Comments:
------------------------------------------------------------------------
[2008-08-02 00:57:22] puts dot email at gmail dot com
Description:
------------
A request for foreach to be key-type agnostic (ideally, assoc's would
be) so that the following is possible:
<?php
class Hash implements ArrayAccess, Iterator {
private $key = array();
private $val = array();
public function offsetGet($key) {
$offset = array_search($key, $this->key);
return $this->val[$offset];
}
public function offsetSet($key, $val) {
$offset = array_search($key, $this->key);
if ($offset === false) {
$this->key[] = $key;
$this->val[] = $val;
} else {
$this->val[$offset] = $val;
}
}
public function offsetExists($key) {
return in_array($key, $this->key);
}
public function offsetUnset($key) {
$offset = array_search($key, $this->key);
unset($this->key[$offset], $this->val[$offset]);
}
public function rewind() {
reset($this->key);
reset($this->val);
}
public function key() {
return current($this->key);
}
public function current() {
return current($this->val);
}
public function next() {
next($this->key);
return next($this->val);
}
public function valid() {
return is_int(key($this->key));
}
}
$h = new hash;
$o0 = new stdclass;
$o1 = new stdclass;
$o2 = new stdclass;
$o3 = new stdclass;
foreach (array($o0, $o1, $o2, $o3) as $i => $o) {
$o->name = "o" . $i;
}
$h[$o0] = $o1;
$h[$o1] = $o2;
$h[$o2] = $o3;
foreach ($h as $key => $val) {}
?>
Reproduce code:
---------------
See description.
Expected result:
----------------
foreach ($h as $key => $val) {
# $key === $o[012]
# $val === $o[123]
}
Actual result:
--------------
foreach ($h as $key => $val) {
# Warning: Illegal type returned from Hash::key()
# $key === 0
# $val === $o[123]
}
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/?id=45684&edit=1