I'm playing with ArrayObject since some days now, but there is a trick that I can't do.
What I want to do :
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) . "
"; // should be MyClass
But $a->bar is a stdClass, and I have a pretty warning in bonus
If I disable the ARRAY_AS_PROPS flag and override the __get and __set methods I'm close :
function __get($key) {
if (! $this->offsetExists($key)) {
$this->offsetSet($key, new self);
}
return $this->offsetGet($key)
}
But then, I have this issue :
$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
Any suggestion ?