查詢

SplObjectStorage::removeAllExcept()函式—用法及示例

「 從SplObjectStorage物件中移除除指定物件以外的所有物件 」


函式名稱:SplObjectStorage::removeAllExcept()

適用版本:PHP 5 >= 5.3.0, PHP 7

函式描述:該方法從SplObjectStorage物件中移除除指定物件以外的所有物件。

用法:

void SplObjectStorage::removeAllExcept ( SplObjectStorage $storage )

引數:

  • $storage: 一個SplObjectStorage物件,其中包含要保留的物件。

返回值:無

示例:

// 建立SplObjectStorage物件
$storage = new SplObjectStorage();

// 建立一些示例物件
$obj1 = new stdClass();
$obj2 = new stdClass();
$obj3 = new stdClass();
$obj4 = new stdClass();

// 將物件新增到SplObjectStorage物件中
$storage->attach($obj1);
$storage->attach($obj2);
$storage->attach($obj3);
$storage->attach($obj4);

// 建立另一個SplObjectStorage物件
$keepStorage = new SplObjectStorage();
$keepStorage->attach($obj1);
$keepStorage->attach($obj2);

// 從$storage中移除除$keepStorage中的物件以外的所有物件
$storage->removeAllExcept($keepStorage);

// 列印剩餘的物件
foreach ($storage as $obj) {
    echo get_class($obj) . "\n";
}

輸出:

stdClass
stdClass

在上面的示例中,我們建立了一個SplObjectStorage物件,並向其新增了四個示例物件。然後,我們建立了另一個SplObjectStorage物件$keepStorage,並向其新增了兩個示例物件$obj1和$obj2。最後,我們使用removeAllExcept()方法從$storage中移除除$keepStorage中的物件以外的所有物件。最終,我們列印剩餘的物件,只有$obj1和$obj2被保留在$storage中。

補充糾錯
熱門PHP函式
分享連結