A Costello
|
Monday 07 July 2008 9:25:28 pm
ArrayAccess is an interface for php classes. It is quite handy. I am sending you a demo.
class Demo implements ArrayAccess, Iterator
{
private $demo = 'default';
private $test = 'default';
private $_offsets = array('Demo', 'Test');
public function setDemo($value)
{
$this->demo = $value;
}
public function getDemo()
{
return $this->demo;
}
public function setTest($value)
{
$this->test = $value;
}
public function getTest()
{
return $this->test;
}
//Foreach Access
public function rewind()
{
$this->cur = 0;
}
public function key()
{
return $this->_offsets[$this->cur];
}
public function current()
{
$function = 'get' . $this->_offsets[$this->cur];
return $this->$function();
}
public function next()
{
++$this->cur;
}
public function valid()
{
return $this->cur < count($this->_offsets);
}
//Array Accessor
function offsetExists($name)
{
return (in_array($name, $this->_offsets));
}
function offsetGet($name)
{
if(in_array($name, $this->_offsets))
{
$function = 'get' . $name;
return $this->$function();
}
return null;
}
function offsetSet($name, $id)
{
if(in_array($name, $this->_offsets))
{
$function = 'set' . $name;
return $this->$function($id);
}
}
function offsetUnset($name)
{
if(in_array($name, $this->_offsets))
{
$function = 'set' . $name;
return $this->$function(null);
}
}
}
$example = new Demo();
echo '<h4>Before Set</h4>';
echo 'demo = ' . $example['Demo'] . '<br>';
echo 'test = ' . $example['Test'] . '<br>';
$example['Demo'] = 'Demo';
$example['Test'] = 'Test';
echo '<h4>After Set</h4>';
echo 'demo = ' . $example['Demo'] . '<br>';
echo 'test = ' . $example['Test'] . '<br>';
echo '<h4>Foreach</h4>';
foreach($example as $key => $value)
{
echo "$key = $value <br>";
}
echo '<h4>Work Around</h4>';
foreach($example as $key => $value)
{
$$key = $value;
//Set to template variable
}
echo 'demo = ' . $Demo . '<br>';
echo 'test = ' . $Test . '<br>';
|