note 11567 deleted from control-structures.foreach by sniper
| From: | sniper@php.net | Date: | Tue, 10 Jun 2003 22:53:15 +0000 |
| Subject: | note 11567 deleted from control-structures.foreach by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-50138@lists.php.net to get a copy of this message | ||
Note Submitter: martin@kouba.at
----
i made the mistake to use a foreach to walk trough an associative array where objects are stored in.
briefly: don't do that! (see below for alternative)
<?
class a {
function a() {
$this->value = "foo";
}
function load($id) {
$this->value = $id;
}
function show() {
echo $this->value." ";
}
}
// create an array of objects
for ($i=1; $i<=3; $objects[$i++] = new a);
foreach ($objects as $key => $obj) {
$obj->load(1);
$obj->show();
}
echo " - ";
foreach ($objects as $key => $obj) {
$obj->show();
}
// this will generate the output
// 1 1 1 - foo foo foo
?>
having found out that foreach makes a copy i had to rethink this because i have a really huge object
modell stored in an array and of course there are member functions changing the contents of the
object.
<?
echo "<br>";
// create an array of objects
foreach ($objects as $key => $obj) {
$objects[$key]->load(2);
$objects[$key]->show();
}
echo " - ";
foreach ($objects as $key => $obj) {
$obj->show();
}
// this will generate the output
// 2 2 2 - 2 2 2
echo "<br>";
foreach (array_keys($objects) as $key) {
$objects[$key]->load(3);
$objects[$key]->show();
}
echo " - ";
foreach (array_keys($objects) as $key) {
$objects[$key]->show();
}
// this will also generate the output
// 3 3 3 - 3 3 3
// AND doesn't make a copy of the array
// which will definitely save memory
// imagine a really huge object modell with
// lot's of sub-objects
?>