note 99236 deleted from class.arrayaccess by googleguy

From: Date: Sun, 25 Nov 2012 05:54:22 +0000
Subject: note 99236 deleted from class.arrayaccess by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192137@lists.php.net to get a copy of this message
Note Submitter: uramihsayibok, gmail, com ---- EDITOR NOTE: You can return by reference in offsetGet as of PHP 5.3.4. If you find yourself facing the dreaded "Indirect modification of overloaded element of $class has no effect" then don't worry too much: there's a clever solution. While you *CANNOT* return by-reference with offsetGet, you can return objects which _also_ implement ArrayAccess... Example: <?php // sanity and error checking omitted for brevity // note: it's a good idea to implement arrayaccess + countable + an // iterator interface (like iteratoraggregate) as a triplet class RecursiveArrayAccess implements ArrayAccess { private $data = array(); // necessary for deep copies public function __clone() { foreach ($this->data as $key => $value) if ($value instanceof self) $this[$key] = clone $value; } public function __construct(array $data = array()) { foreach ($data as $key => $value) $this[$key] = $value; } public function offsetSet($offset, $data) { if (is_array($data)) $data = new self($data); if ($offset === null) { // don't forget this! $this->data[] = $data; } else { $this->data[$offset] = $data; } } public function toArray() { $data = $this->data; foreach ($data as $key => $value) if ($value instanceof self) $data[$key] = $value->toArray(); return $data; } // as normal public function offsetGet($offset) { return $this->data[$offset]; } public function offsetExists($offset) { return isset($this->data[$offset]); } public function offsetUnset($offset) { unset($this->data); } } $a = new RecursiveArrayAccess(); $a[0] = array(1=>"foo", 2=>array(3=>"bar", 4=>array(5=>"bz"))); // oops. typo $a[0][2][4][5] = "baz"; //var_dump($a); //var_dump($a->toArray()); // isset and unset work too //var_dump(isset($a[0][2][4][5])); // equivalent to $a[0][2][4]->offsetExists(5) //unset($a[0][2][4][5]); // equivalent to $a[0][2][4]->offsetUnset(5); // if __clone wasn't implemented then cloning would produce a shallow copy, and $b = clone $a; $b[0][2][4][5] = "xyzzy"; // would affect $a's data too //echo $a[0][2][4][5]; // still "baz" ?>

« previous php.notes (#192137) next »