Detaching the current entry from the storage prevents SplObjectStorage::next() to operate.
Example as a PHPUnit-test:
<?php
public function testDetachingCurrentPreventsNext()
{
$storage = new SplObjectStorage;
$storage->attach(new stdClass);
$storage->attach(new stdClass);
$storage->rewind();
$iterated = 0;
$expected = $storage->count();
while ($storage->valid()) {
$iterated++;
$storage->detach($storage->current());
$storage->next();
}
$this->assertEquals($expected, $iterated);
}
?>
This test will fail, for the iteration will never reach the second stdClass.
SplObjectStorage::next() obviously relies on the current element to be valid.
If you want to detach objects during iterations, you should dereference objects, before you call next() and detach the reference after next():
<?php
public function testDetachingReferenceAfterNext()
{
$storage = new SplObjectStorage;
$storage->attach(new stdClass);
$storage->attach(new stdClass);
$storage->rewind();
$iterated = 0;
$expected = $storage->count();
while ($storage->valid()) {
$iterated++;
$object = $storage->current();
$storage->next();
$storage->detach($object);
}
$this->assertEquals($expected, $iterated);
}
?>
This test will pass.
SplObjectStorage::detach
(PHP 5 >= 5.1.0)
SplObjectStorage::detach — Retire un objet du stockage
Valeurs de retour
Aucune valeur n'est retournée.
Exemples
Exemple #1 Exemple avec SplObjectStorage::detach()
<?php
$o = new StdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->detach($o);
var_dump(count($s));
?>
L'exemple ci-dessus va afficher quelque chose de similaire à :
int(1) int(0)
Voir aussi
- SplObjectStorage::attach() - Ajoute un objet dans le stockage
- SplObjectStorage::removeAll() - Retire les objets d'un stockage qui appartienne à un autre stockage
r dot wilczek at web-appz dot de
29-Apr-2010 07:18
