PHP Doku:: Removes an object from the storage - splobjectstorage.detach.html

Verlauf / Chronik / History: (2) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSonstige GrunderweiterungenStandard PHP Library (SPL)DatenstrukturenThe SplObjectStorage classSplObjectStorage::detach

Ein Service von Reinhard Neidl - Webprogrammierung.

The SplObjectStorage class

<<SplObjectStorage::current

SplObjectStorage::getInfo>>

SplObjectStorage::detach

(PHP 5 >= 5.1.0)

SplObjectStorage::detachRemoves an object from the storage

Beschreibung

public void SplObjectStorage::detach ( object $object )

Removes the object from the storage.

Parameter-Liste

object

The object to remove.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

Beispiel #1 SplObjectStorage::detach() example

<?php
$o 
= new StdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->detach($o);
var_dump(count($s));
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

int(1)
int(0)

Siehe auch


Ein BenutzerBeitrag:
- Beiträge aktualisieren...
r dot wilczek at web-appz dot de
30.04.2010 10:18
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.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)