You may remove all elements by passing empty SplObjectStorage
$splStorage->removeAllExcept(new SplObjectStorage());
PHP - Manual: SplObjectStorage::removeAllExcept
2024-11-15
(PHP 5 >= 5.3.6, PHP 7, PHP 8)
SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage
Removes all objects except for those contained in another storage from the current storage.
storage
The storage containing the elements to retain in the current storage.
Returns the number of remaining objects.
示例 #1 SplObjectStorage::removeAllExcept() example
<?php
$a = (object) 'a';
$b = (object) 'b';
$c = (object) 'c';
$foo = new SplObjectStorage;
$foo->attach($a);
$foo->attach($b);
$bar = new SplObjectStorage;
$bar->attach($b);
$bar->attach($c);
$foo->removeAllExcept($bar);
var_dump($foo->contains($a));
var_dump($foo->contains($b));
?>
以上例程的输出类似于:
bool(false) bool(true)
You may remove all elements by passing empty SplObjectStorage
$splStorage->removeAllExcept(new SplObjectStorage());
The example Kirk provided is not the best option, there's a method "removeAll" that you can pass the SplObjectStore itself, and as the name says, remove all stored objects.
官方地址:https://www.php.net/manual/en/splobjectstorage.removeallexcept.php