note 114880 added to control-structures.foreach
| From: | nehuen | Date: | Sun, 20 Apr 2014 03:27:50 +0000 |
| Subject: | note 114880 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-199299@lists.php.net to get a copy of this message | ||
foreach by reference internally deleted and created a new reference in each iteration, so it is not
possible to directly use this value as a variable parameter valuesââ, look at the
following example where the problem is observed and a possible solution:
<?php
class test
{
private $a = false;
private $r = null;
public function show(&$v)
{
if(!$this->a)
{
$this->a = true;
$this->r = &$v;
}
var_dump($this->r);
}
public function reset()
{
$this->a = false;
}
}
$t = new test();
$a = array(array(1,2),array(3,4),array(5,6));
foreach($a as &$p)
$t->show($p);
/* Output obtain:
array (size=2)
0 => int 1
1 => int 2
array (size=2)
0 => int 1
1 => int 2
array (size=2)
0 => int 1
1 => int 2
*/
$t->reset();
foreach($a as $p)
{
$b = &$p;
$t->show($b);
}
/* Output obtain:
array (size=2)
0 => int 1
1 => int 2
array (size=2)
0 => int 3
1 => int 4
array (size=2)
0 => int 5
1 => int 6
*/
----
Server IP: 72.52.91.14
Probable Submitter: 190.7.251.125
----
Manual Page -- http://php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/114880
Del: integrated -- https://master.php.net/note/delete/114880/integrated
Del: useless -- https://master.php.net/note/delete/114880/useless
Del: bad code -- https://master.php.net/note/delete/114880/bad+code
Del: spam -- https://master.php.net/note/delete/114880/spam
Del: non-english -- https://master.php.net/note/delete/114880/non-english
Del: in docs -- https://master.php.net/note/delete/114880/in+docs
Del: other reasons-- https://master.php.net/note/delete/114880
Reject -- https://master.php.net/note/reject/114880
Search -- https://master.php.net/manage/user-notes.php