If you plan to derive your own class from ArrayObject, and wish to maintain complete ArrayObject functionality (such as being able to cast to an array), it is necessary to use ArrayObject's own private property "storage".
Since that is impossible to do directly, you must use ArrayObject's offset{Set,Get,Exists,Unset} methods to manipulate it indirectly.
As a side benefit, this means you inherit all the iteration and other functions in complete working order.
This may sound obvious to someone who has never implemented their own ArrayObject class... but it is far from so.
<?php
class MyArrayObject extends ArrayObject {
static $debugLevel = 2;
static public function sdprintf() {
if (static::$debugLevel > 1) {
call_user_func_array("printf", func_get_args());
}
}
public function offsetGet($name) {
self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
}
public function offsetSet($name, $value) {
self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
}
public function offsetExists($name) {
self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
}
public function offsetUnset($name) {
self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
}
}
$mao = new MyArrayObject();
$mao["name"] = "bob";
$mao["friend"] = "jane";
print_r((array)$mao);
?>
If you wish to use the "Array as Properties" flag, you simply need to include this in your constructor:
<?php parent::setFlags(parent::ARRAY_AS_PROPS); ?>
This will allow you to do things such as the below example, without overriding __get or __set .
<?php
$mao->name = "Phil";
echo $mao["name"]; ?>