note 101215 deleted from control-structures.foreach by googleguy
| From: | googleguy@php.net | Date: | Wed, 14 Nov 2012 22:23:53 +0000 |
| Subject: | note 101215 deleted from control-structures.foreach by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191952@lists.php.net to get a copy of this message | ||
Note Submitter: fabiolimasouto at gmail dot com
----
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.