带有ARRAY_AS_PROPS的嵌套ArrayObject

时间:2017-02-10 14:06:22

标签: php arrayobject

我几天以来一直在玩ArrayObject,但有一个技巧我无法做到。

我想做什么:

MyClass extends ArrayObject {
    public function __construct($input = []) {
        parent::__construct($input, self::ARRAY_AS_PROPS);
    }
}

$a = new MyClass();
$a->foo = 'bar';
var_dump($a->getArrayCopy()); // there should be only one key : "foo"
$a->bar->baz = 'foo';
var_dump($a->getArrayCopy()); // there should be only two keys : "foo", "bar"
echo get_class($a->bar) . "\n"; // should be MyClass

但$ a-> bar是stdClass,我在奖金方面有一个非常警告

如果我禁用ARRAY_AS_PROPS标志并覆盖__get和__set方法,我就关闭了:

function __get($key) {
   if (! $this->offsetExists($key)) {
       $this->offsetSet($key, new self);
   }
   return $this->offsetGet($key)
}

但是,我有这个问题:

$a = new MyClass();
$a->foo = 'bar';
var_dump($a->getArrayCopy()); // there is one key ("foo") which is correct

// but when I do anything with the key without affecting some data
isset($a->bar);
var_dump($a->getArrayCopy()); // Now I also have the key "bar" which is not correct

有什么建议吗?

0 个答案:

没有答案