downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

SplObjectStorage::getHash> <SplObjectStorage::current
[edit] Last updated: Fri, 25 May 2012

view this page in

SplObjectStorage::detach

(PHP 5 >= 5.1.0)

SplObjectStorage::detachオブジェクトをストレージから取り除く

説明

public void SplObjectStorage::detach ( object $object )

オブジェクトをストレージから取り除きます。

パラメータ

object

取り除きたいオブジェクト。

返り値

値を返しません。

例1 SplObjectStorage::detach() の例

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

上の例の出力は、 たとえば以下のようになります。

int(1)
int(0)

参考



add a note add a note User Contributed Notes SplObjectStorage::detach
r dot wilczek at web-appz dot de 30-Apr-2010 01: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.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites