Custom foreach results for dynamic proxy class - magic methods?

I need to serialize a proxy class. The class uses __set and __get to store values โ€‹โ€‹in an array. I want serialization to look like it's just a flat object. In other words, my class looks like this:

class Proxy { public $data = array(); public function __get($name) { return $data[$name] } } 

and I want the foreach loop to return all keys and values โ€‹โ€‹in $ data when I say:

 foreach($myProxy as $key) 

Is it possible?

+4
source share
2 answers
 class Proxy implements IteratorAggregate { public $data = array(); public function __get($name) { return $data[$name]; } public function getIterator() { $o = new ArrayObject($this->data); return $o->getIterator(); } } $p = new Proxy(); $p->data = array(2, 4, 6); foreach ($p as $v) { echo $v; } 

Exit: 246 .

For more information, see Iterating Objects in PHP Documents.

+7
source

You want to implement the SPL iterator interface

Something like that:

 class Proxy implements Iterator { public $data = array(); public function __get($name) { return $data[$name] } function rewind() { reset($this->data); $this->valid = true; } function current() { return current($this->data) } function key() { return key($this->data) } function next() { next($this->data); } function valid() { return key($this->data) !== null; } } 
+3
source

Source: https://habr.com/ru/post/1285702/


All Articles