如果您計劃從 ArrayObject 衍生自己的類別,並希望維持完整的 ArrayObject 功能(例如能夠轉換為陣列),則必須使用 ArrayObject 自己的私有屬性 "storage"。
由於無法直接執行此操作,您必須使用 ArrayObject 的 offset{Set,Get,Exists,Unset} 方法間接操作它。
另一個好處是,這表示您繼承了所有迭代和其他功能,並能完整運作。
對於從未實作自己的 ArrayObject 類別的人來說,這可能聽起來很明顯...但事實遠非如此。
<?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);
?>
如果您希望使用「陣列如同屬性」旗標,您只需在建構子中加入此行
<?php parent::setFlags(parent::ARRAY_AS_PROPS); ?>
這將允許您執行以下範例之類的操作,而無需覆寫 __get 或 __set。
<?php
$mao->name = "Phil";
echo $mao["name"]; ?>