note 101215 added to control-structures.foreach

From: Date: Thu, 02 Dec 2010 15:39:15 +0000
Subject: note 101215 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-174571@lists.php.net to get a copy of this message
I've been using this foreach structure for two years or so now, and just figured something new which i hadn't realized before, please have a look at this: <?php class Test { private $data; function &data() { return $this->data; } function getData() { return $this->data; } } $obj = new Test; $data =& $obj->data(); $array = array('a','b','c'); foreach($array as $data) { } echo $obj->getData(); // OUTPUTS: "c"!!! ?> What I can say from this is that if you pass a reference to the data holder of the foreach structure instead of a non-declared or normal (non-reference) variable, you will be able to fill that same (referenced) space in memory without creating a new one. Note that this is slightly different as explained in the manual above: <?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) unset($value); // break the reference with the last element ?> In this case $value will simply point to the original addresses of each $array's elements in each iteration. In my example the $data variable is before anything already pointing to another address elsewhere and will have THAT memory location filled in each iteration!!! Hope I've made this somewhat understandable. ---- Server IP: 69.147.83.197 Probable Submitter: 201.41.24.93 ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- https://master.php.net/note/edit/101215 Del: integrated -- https://master.php.net/note/delete/101215/integrated Del: useless -- https://master.php.net/note/delete/101215/useless Del: bad code -- https://master.php.net/note/delete/101215/bad+code Del: spam -- https://master.php.net/note/delete/101215/spam Del: non-english -- https://master.php.net/note/delete/101215/non-english Del: in docs -- https://master.php.net/note/delete/101215/in+docs Del: other reasons-- https://master.php.net/note/delete/101215 Reject -- https://master.php.net/note/reject/101215 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#174571) next »