note 32799 added to control-structures.foreach
| From: | reza at rack1 dot php dot net | Date: | Sat, 07 Jun 2003 09:51:06 +0000 |
| Subject: | note 32799 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-49934@lists.php.net to get a copy of this message | ||
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.
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+32799
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+32799&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+32799&report=yes