略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: SplObjectStorage::detach

2024-11-13

SplObjectStorage::detach

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObjectStorage::detachRemoves an object from the storage

说明

public SplObjectStorage::detach(object $object): void

Removes the object from the storage.

参数

object

The object to remove.

返回值

没有返回值。

范例

示例 #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));
?>

以上例程的输出类似于:

int(1)
int(0)

参见

add a noteadd a note

User Contributed Notes 3 notes

up
9
r dot wilczek at web-appz dot de
12 years ago
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.
up
3
alan dot bem at gmail dot com
8 years ago
SplObjectSotage::detach() has a bug - it rewinds internal array pointer.
Remember that - when looping over the storage - as it has no workaround.

https://bugs.php.net/bug.php?id=65629&edit=2
up
0
Hayley Watson
4 years ago
No complaints from SplObjectStorage if you try to detach an object that isn't in the collection; it's a no-op.

<?php

$o
= new StdClass;
$t = new StdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->detach($t); // Didn't attach this one.
var_dump(count($s));

?>

官方地址:https://www.php.net/manual/en/splobjectstorage.detach.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3