views:

122

answers:

2

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

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

and I want a foreach loop to return all the keys and values in $data, when I say:

foreach($myProxy as $key)

Is this possible?

+2  A: 

You want to implement the SPL iterator interface

Something like this:

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;
    }
}
Greg
I don't have control over the code that will be doing the iterating. It is a 3rd-party library, and I want my proxy to play nice with it. It uses a foreach. Am I right in assuming that implementing the interface would require the person iterating to use the interface functions, or does it do some magic behind the scenes?
Sean Clark Hess
The iterator interface is magic - it lets you use foreach() over your object
Greg
Thanks for the info!
Sean Clark Hess
+5  A: 
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;
}

Output is: 246.

See Object Iteration in the PHP docs for more details.

Ayman Hourieh