Page 1 of 1
Object Recursion
Posted: Tue Mar 25, 2008 1:59 am
by aliasxneo
I know this is possible because I did it once before but unfortunately I lost my code and I can't remember exactly how I went about doing it now (was a few years ago when I made it).
What I'm looking to do is to allow my class to be recursive. So when applied like thus:
Code: Select all
$class = new Class();
foreach($class as $key => $value)
{
// Do stuff //
}
It would act like any other array and loop through all the elements returning the proper key and it's associated value. I believe I was implementing the Iterator class but again I'm not positive. Can someone shed some light on this? Thanks.
Re: Object Recursion
Posted: Tue Mar 25, 2008 2:05 am
by Christopher
Re: Object Recursion
Posted: Tue Mar 25, 2008 2:12 am
by aliasxneo
I actually wasn't even aware such a function existed. It doesn't exactly solve my original intent though because I specifically wanted the class to act as an iterator without having to use an extra layer like the function above.
* EDIT *
I managed to find my old class and got it working now. Here is the code if anyone was interested:
Code: Select all
<?php
class Section implements Iterator
{
private $cell;
private $objects;
function __construct()
{
$this->cell = Life::getCell();
}
// Overloader; called when a class variable is referenced //
function __get($object)
{
// If we dont have anything in our object array about it, it doesn't exist //
if (!isset($this->objects[$object]))
{
return false;
} else {
return $this->objects[$object];
}
}
// Overloader; called when a class variable is set //
function __set($object, $value)
{
// Add it to our object array //
$this->objects[$object] = $value;
}
public function rewind()
{
reset($this->objects);
}
public function current()
{
$var = current($this->objects);
return $var;
}
public function key()
{
$var = key($this->objects);
return $var;
}
public function next()
{
$var = next($this->objects);
return $var;
}
public function valid()
{
$var = $this->current() !== false;
return $var;
}
public function newSection($section)
{
/** Basically this creates a new layer so that this new section
has the same functionality as this one */
$this->objects[$section] = $this->cell->DNA->getNucleotide("Section");
}
}
?>