note 41645 deleted from control-structures.foreach by googleguy

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

« previous php.notes (#191987) next »