note 108687 modified in class.arrayobject by danbrown

From: Date: Thu, 17 May 2012 18:18:34 +0000
Subject: note 108687 modified in class.arrayobject by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-188041@lists.php.net to get a copy of this message
Please note, that there&#39;s another potential &#34;gotcha&#34; in using ArrayObject like regular array. Objects are reference types and arrays are value types. Consider following piece of code:&#13;&#10;&#60;?php&#13;&#10;&#13;&#10;class MyArrayObject extends ArrayObject&#13;&#10;{&#13;&#10;&#9;protected $data = array();&#13;&#10;&#9;public function offsetGet($name) {&#13;&#10;&#9;&#9;return $this-&#62;data[$name];&#13;&#10;&#9;}&#13;&#10;&#9;public function offsetSet($name, $value) {&#13;&#10;&#9;&#9;$this-&#62;data[$name] = $value;&#13;&#10;&#9;}&#13;&#10;&#9;public function offsetExists($name) {&#13;&#10;&#9;&#9;return isset($this-&#62;data[$name]);&#13;&#10;&#9;}&#13;&#10;&#9;public function offsetUnset($name) {&#13;&#10;&#9;&#9;unset($this-&#62;data[$name]);&#13;&#10;&#9;}&#13;&#10;}&#13;&#10;&#13;&#10;function my_array_modify($data) { //note - not reference &#38;$data&#13;&#10;&#9;$data[&#39;b&#39;] = 2;&#13;&#10;}&#13;&#10;&#13;&#10;$regularArray = array();&#13;&#10;$arrayObject = new MyArrayObject();&#13;&#10;&#13;&#10;$regularArray[&#39;a&#39;] = 1;&#13;&#10;$arrayObject[&#39;a&#39;] = 1;&#13;&#10;my_array_modify($regularArray);&#13;&#10;my_array_modify($arrayObject);&#13;&#10;var_dump($regularArray[&#39;b&#39;]); // PHP Notice: Undefined index: b&#13;&#10;var_dump($arrayObject[&#39;b&#39;]); // int(2)&#13;&#10;?&#62; --was-- Please note, that there's another potential "gotcha" in using ArrayObject like regular array. Objects are reference types and arrays are value types. Consider following piece of code: <?php class MyArrayObject extends ArrayObject { protected $data = array(); public function offsetGet($name) { return $this->data[$name]; } public function offsetSet($name, $value) { $this->data[$name] = $value; } public function offsetExists($name) { return isset($this->data[$name]); } public function offsetUnset($name) { unset($this->data[$name]); } } function my_array_modify($data) { //note - not reference &$data $data['b'] = 2; } $regularArray = array(); $arrayObject = new MyArrayObject(); $regularArray['a'] = 1; $arrayObject['a'] = 1; my_array_modify($regularArray); my_array_modify($arrayObject); var_dump($regularArray['b']); // PHP Notice: Undefined index: b var_dump($arrayObject['b']); // int(2) http://php.net/manual/en/class.arrayobject.php

« previous php.notes (#188041) next »