note 97644 added to splobjectstorage.detach

From: Date: Fri, 30 Apr 2010 08:18:38 +0000
Subject: note 97644 added to splobjectstorage.detach
Groups: php.notes 
Request: Send a blank email to php-notes+get-168803@lists.php.net to get a copy of this message
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. ---- Server IP: 85.214.154.209 Probable Submitter: 87.79.200.243 ---- Manual Page -- http://www.php.net/manual/en/splobjectstorage.detach.php Edit -- https://master.php.net/note/edit/97644 Del: integrated -- https://master.php.net/note/delete/97644/integrated Del: useless -- https://master.php.net/note/delete/97644/useless Del: bad code -- https://master.php.net/note/delete/97644/bad+code Del: spam -- https://master.php.net/note/delete/97644/spam Del: non-english -- https://master.php.net/note/delete/97644/non-english Del: in docs -- https://master.php.net/note/delete/97644/in+docs Del: other reasons-- https://master.php.net/note/delete/97644 Reject -- https://master.php.net/note/reject/97644 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168803) next »