Добрый день. Есть необходимость использовать класс как массив.
| Код | class Test implements ArrayAccess { private static $obj = array();
public function __set($name, $value) { self::$obj[$name] = $value; } public function __get($name) { return (isset(self::$obj[$name])?self::$obj[$name]:null); } public function remove($key) { unset(self::$obj[$key]); }
public function offsetExists($offset) { return isset(self::$obj[$offset]); }
public function offsetGet($offset) { return $this->__get($offset); }
public function offsetSet($offset, $value) { $this->__set($offset, $value); }
public function offsetUnset($offset) { unset(self::$obj[$offset]); } }
$test = new Test();
$test->key = 'value'; echo $test->key.'<br />'; // value echo $test['key'].'<br />'; // value
$test->key = array('q' => 'qqq', 'w' => 'www'); var_dump($test->key);
echo $test['key']['q'].'<br />'; // qqq
|
А вот если я захочу сделать так
| Код | $test['key']['q'] = 'new q';
|
то получаю ошибку
| Цитата | Notice: Indirect modification of overloaded element of Test has no effect
|
Можно ли сделать так, чтобы эти способы работали?
| Код | $test['array']['key'][0] = 0; $test['array']['key'][1] = 1;
$test['new'] = array('q' => 1, 'w' => 2); $test['new']['q'] = 0;
|
|