note 32799 deleted from control-structures.foreach by sniper

From: Date: Wed, 08 Oct 2003 04:04:42 +0000
Subject: note 32799 deleted from control-structures.foreach by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-58000@lists.php.net to get a copy of this message
Note Submitter: reza at sharif dot edu ---- If your array holds references to some objects, using foreach to traverse the array will actually clone the objects rather than giving you access to your original objects. This might cause some [difficult-to-find] problems. // THIS IS WRONG $collect = array(); $collectp[] =& new ObjectType(); $collectp[] =& new ObjectType(); foreach ($collect as $val) { $val->doOperation(); } In order to overcome this, you need a mechanism to extract the object references (stored in the array) rather than having them COPIED by the implicit assignment inside the foreach loop. Instead of going for a dirty list()-based iteration, we can use array_keys() to make an array out of the _keys_ of the original array, and then use the keys to do the referencing manually. This enables us to use the elegant foreach loop. $array_keys = array_keys($collect); foreach ($array_keys as $thekey) { $collect[$thekey]->doOperation(); } I believe it would have been much easier if PHP treated references as references, and didn't try to COPY the whole things around, everytime seeing a reference in the right side of an assignment.

« previous php.notes (#58000) next »