Ich denke ich habe einen Bug in PHP gefunden. Betroffen ist das SimpleXML-Modul in Verbindung mit foreach. Betroffen sind alle PHP-Version bis einschliesslich 5.2.10.
Der Bug schlägt zu, wenn man schreibend (Zeile 37) auf ein SimpleXML-Objekt in einer Foreach-Schleife zugreift. In dem Moment scheint es den internen Zähler des Iterators zu verstellen. Das Resultat ist eine Endlosschleife. Das Foreach-Konstrukt kann nicht mehr verlassen werden.
Das Problem tritt nicht auf, wenn man dies in einer For-Schleife macht.
Update: Ich habe ein Bug-Report verfasst.
Der PHP-Code, welcher den Fehler reproduziert, sieht folgendermaßen aus und wurde mit den PHP-Version: 5.2.6 (win), 5.2.9 (win) und 5.2.9-0.dotdeb.2 (lin) getestet:
Download Code!
<?php
$xmlData = <<<HERE
<root>
<child>
<name>A child</name>
<info>
<version>1</version>
</info>
</child>
<child>
<name>B child</name>
<info>
<version>2</version>
</info>
</child>
<child>
<name>C child</name>
<info>
<version>2</version>
</info>
</child>
<child>
<name>D child</name>
<info>
<version>3</version>
</info>
</child>
</root>
HERE;
$xml = simplexml_load_string($xmlData);
$i = -1;
foreach ($xml as $xi => $child) {
++$i;
echo 'I: '.$i.' Xi: '.$xi.' Count : '.count($xml).' '.$xml->child[$i]->name.' => '.$child->name.' v:'.$child->info->version."\n"; $xml->child[$i]->info->version = rand(1,9); if($i > 10) {
echo "Too many iterations"; break;
}
}
$xml = simplexml_load_string($xmlData);
for($i = 0, $size = count($xml); $i < $size; ++$i) { echo 'I: '.$i.' Count : '.count($xml).' '.$xml->child[$i]->name."\n"; $xml->child[$i]->info->version = rand(1,9); if($i > 10) {
echo "Too many iterations"; break;
}
}
?>
Ausgabe:
I: 0 Xi: child Count : 4 A child => A child v:1
I: 1 Xi: child Count : 4 B child => B child v:2
I: 2 Xi: child Count : 4 C child => B child v:6
I: 3 Xi: child Count : 4 D child => B child v:6
Notice: Trying to get property of non-object in simplexmlbug.php on line 36
I: 4 Xi: child Count : 4 => B child v:6
Notice: Trying to get property of non-object in simplexmlbug.php on line 36
I: 5 Xi: child Count : 5 => B child v:6
Notice: Trying to get property of non-object in simplexmlbug.php on line 36
I: 6 Xi: child Count : 6 => B child v:6
Notice: Trying to get property of non-object in simplexmlbug.php on line 36
I: 7 Xi: child Count : 7 => B child v:6
Notice: Trying to get property of non-object in simplexmlbug.php on line 36
I: 8 Xi: child Count : 8 => B child v:6
Notice: Trying to get property of non-object in simplexmlbug.php on line 36
I: 9 Xi: child Count : 9 => B child v:6
Notice: Trying to get property of non-object in simplexmlbug.php on line 36
I: 10 Xi: child Count : 10 => B child v:6
Notice: Trying to get property of non-object in simplexmlbug.php on line 36
I: 11 Xi: child Count : 11 => B child v:6
Too many iterationsI: 0 Count : 4 A child
I: 1 Count : 4 B child
I: 2 Count : 4 C child
I: 3 Count : 4 D child