note 41645 added to control-structures.foreach
| From: | scott at slerman dot net | Date: | Sun, 18 Apr 2004 00:27:45 +0000 |
| Subject: | note 41645 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-68273@lists.php.net to get a copy of this message | ||
Apparently the behavior of foreach with classes changed in PHP5. Normally, foreach operates on a
copy of the array. If you have something like
<?php
foreach ($array as $value){
$value = "foo";
}
?>
the original array will not be modified. However, testing this code on PHP5RC1
<?php
class foobar {
var $a;
var $b;
function foobar(){
$this->a = "foo";
$this->b = "bar";
}
}
$a = new foobar;
$b = new foobar;
$c = new foobar;
$arr = array('a' => $a, 'b' => $b, 'c' => $c);
foreach ($arr as $e){
$e->a = 'bah';
$e->b = 'blah';
}
var_dump($arr);
?>
resulted in the following output:
array(3) {
["a"]=>
object(foobar)#1 (2) {
["a"]=>
string(3) "bah"
["b"]=>
string(4) "blah"
}
["b"]=>
object(foobar)#2 (2) {
["a"]=>
string(3) "bah"
["b"]=>
string(4) "blah"
}
["c"]=>
object(foobar)#3 (2) {
["a"]=>
string(3) "bah"
["b"]=>
string(4) "blah"
}
}
It would seem that classes are actually passed by reference in foreach, or at least that methods are
called on the original objects.
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41645
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41645&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41645&report=yes
Search -- http://master.php.net/manage/user-notes.php