PHP Objects as Artificial Arrays
I have an object that implements ArrayAccess , Iterator and Countable . This creates an almost perfect masking of the array. I can access it with offsets ( $object[foo]
), I can throw it in foreach
-loop, and more.
But what I can not do is give it a function of the iterator's own array ( next()
, reset()
, current()
, key()
), although I have applied the necessary methods of Iterator. PHP seems to be trying hard to iterate over its member variables and also completely ignores the iterator-method.
Is there an interface that would bind the object to the rest of the array's move functions, or am I sticking with what I have?
Update: Iterator Aggregate is not the answer either. Although used in foreach
-loops, the main array iterator functions do not call methods.
source to share
Recent changes in PHP prevent the manipulation of the ArrayIterators form using standard array functions (reset, next, etc.).
This should be repaired soon: http://news.php.net/php.internals/42015
source to share
One way to make this work is to define your own iterator in a separate class and then tell the main class that it is using this new iterator instead of the default one.
class MyIterator implements Iterator {
public function key() {
//
}
public function rewind() {
//
}
// etc.
}
class MyMainClass implements IteratorAggregate {
private $_data = array();
// getIterator is required for the IteratorAggregate interface.
public function getIterator() {
return new MyIterator($this->_data);
}
// etc.
}
Then you should have the same control you want. (And you can reuse your MyIterator for multiple classes).
No testing has been done above, but the principle is correct, I believe.
Hope this helps!
source to share
Is ArrayIterator not what you are looking for? Or how about ArrayObject , which seems to be the SPL interface for what you are trying to achieve.
source to share