Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP BUG [SPL]: __get method is not calling
<?php
class MyArrayObject extends \ArrayObject
{
public function offsetGet($index)
{
if (!parent::offsetExists($index)) {
parent::offsetSet($index, new MyArrayObject(array(), \ArrayObject::ARRAY_AS_PROPS));
}
return parent::offsetGet($index);
}
// this magic method not called on non-exist property access
public function __get($index)
{
return $this->offsetGet($index);
}
}
$arrObj1 = new \MyArrayObject(array(), \ArrayObject::ARRAY_AS_PROPS);
// error: undefined index foo BP_VAR_RW
$arrObj1->foo->bar->baz = 99;
// OK
$bar = $arrObj1->foo->bar;
$bar->baz = 99;
// OK
$arrObj1['foo']['bar']['baz'] = 99;
class OtherArrayObject implements \ArrayAccess
{
private $storage = array();
public function offsetExists($offset)
{
return isset($this->storage[$offset]);
}
public function offsetGet($offset)
{
if (!$this->offsetExists($offset)) {
$this->offsetSet($offset, new OtherArrayObject());
}
return $this->storage[$offset];
}
public function offsetSet($offset, $value)
{
$this->storage[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->storage[$offset]);
}
public function __get($name)
{
return $this->offsetGet($name);
}
public function __set($name, $value)
{
return $this->offsetSet($name, $value);
}
public function __isset($name)
{
return isset($this->storage[$name]);
}
public function __unset($name)
{
unset($this->storage[$name]);
}
}
$arrObj2 = new OtherArrayObject();
// OK:
$arrObj2->foo->bar->baz = 99;
// OK:
$arrObj2['foo']['bar']['baz'] = 99;
var_dump($arrObj2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment