Thursday, November 22, 2007

Mixing array with objects

The SPL extension allows us to use objects as array. One way to do this is to use the class predefined ArrayObject. Another way is to implement an interface ArrayAccess to access our data as if they were an array. An example of this

class MyArray implements ArrayAccess {
private $data;

public function __construct($array = array())
{
$this->data = $array;
}

public function offsetGet($key)
{
return $this->data[$key];
}

public function offsetSet($key, $value)
{
return $this->data[$key] = $value;
}
public function offsetExists($key)
{
return isset($this->data[$key]);
}
public function offsetUnset($key)
{
unset($this->data[$key]);
}

public function avg()
{
if (count($this->data) > 0)
{
return array_sum($this->data) / count($this->data);
}
}
}
//echo 0xFACEB00C >> 2;
$array = new MyArray(array(1, 2, 3, 4));
echo (int)isset($array[0]);
echo $array[0];

unset($array[1]);
echo (int)isset($array[1]); //throw an ugly notice
echo $array[1];

$array[1] = 4;
echo (int)isset($array[1]);
echo $array[1];

echo $array->avg();

No comments: