當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


PHP SplObjectStorage removeAllExcept()用法及代碼示例


SplObjectStorage::removeAllExcept()函數是PHP中的一個內置函數,用於從存儲中刪除所有對象,但另一個存儲所包含的對象除外。

用法:

int SplObjectStorage::removeAllExcept()

參數:該函數接受單個參數$obj,該參數指定要保留的對象存儲。


返回值:該函數不返回任何值。

以下示例程序旨在說明PHP中的SplObjectStorage::removeAllExcept()函數:

程序1:

<?php 
  
$obj1 = new StdClass; 
$obj2 = new StdClass; 
$obj3 = new StdClass; 
  
$gfg1 = new SplObjectStorage(); 
$gfg1[$obj1] = "Geeks"; 
  
$gfg2 = new SplObjectStorage(); 
$gfg2[$obj1] = "GFG"; 
$gfg2[$obj2] = "GeeksClasses"; 
$gfg2[$obj3] = "SUDO"; 
  
// Count all existing objects 
var_dump(count($gfg2)); 
  
// Remove all objects of $gfg2 from $gfg2 
$gfg2->removeAllExcept($gfg1); 
  
// Print result after removeAll 
var_dump(count($gfg2)); 
?>
輸出:
int(3)
int(1)

程序2:

<?php 
  
$obj1 = new StdClass; 
$obj2 = new StdClass; 
  
$gfg1 = new SplObjectStorage(); 
$gfg1[$obj1] = "Geeks"; 
  
$gfg2 = new SplObjectStorage(); 
$gfg2[$obj1] = "GFG"; 
$gfg2[$obj2] = "GeeksClasses"; 
  
// Count and print all existing objects 
var_dump(count($gfg2)); 
  
// Remove all objects of $gfg1 from $gfg2 
$gfg2->removeAllExcept($gfg1); 
  
// Print result   
var_dump(count($gfg2)); 
  
// Result remains same 
$gfg2->removeAllExcept($gfg2); 
  
// Print result   
var_dump(count($gfg2)); 
  
?>
輸出:
int(2)
int(1)
int(1)

參考: https://www.php.net/manual/en/splobjectstorage.removeallexcept.php



相關用法


注:本文由純淨天空篩選整理自R_Raj大神的英文原創作品 PHP | SplObjectStorage removeAllExcept() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。