Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 659
Sean Clark Hess Avatar asked Dec 30 '22 22:12

Sean Clark Hess


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;
}

Output is: 246.

See Object Iteration in the PHP docs for more details.

like image 70
Ayman Hourieh Avatar answered Jan 13 '23 12:01

Ayman Hourieh


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;
    }
}
like image 39
Greg Avatar answered Jan 13 '23 12:01

Greg