개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.03.04 16:48

SplObjectStorage::removeAllExcept 사용 방법에 대한 질문

  • 화이트해커연구가 12일 전 2025.03.04 16:48
  • 9
    1
안녕하세요 선생님, SplObjectStorage::removeAllExcept 메서드를 사용하여 객체를 제거하는 방법에 대해 궁금합니다.

SplObjectStorage::removeAllExcept 메서드는 특정 객체를 제외한 모든 객체를 삭제하는 데 사용됩니다. 예를 들어, 다음과 같은 코드를 생각해 볼 수 있습니다.

php

$storage = new SplObjectStorage();

$obj1 = new stdClass();

$obj2 = new stdClass();

$obj3 = new stdClass();



$storage->attach($obj1);

$storage->attach($obj2);

$storage->attach($obj3);



// 특정 객체를 제외한 모든 객체를 삭제

$storage->removeAllExcept($obj3);



이 코드는 `$obj3`를 제외한 모든 객체를 삭제하려고 시도합니다. 그러나, `$obj3`는 $storage에 아직 첨부되어 있지 않기 때문에, `$obj3`는 삭제되지 않습니다.

이러한 상황에서 `$obj3`를 제거하고, `$storage`에 첨부되어 있는 모든 객체를 삭제하고 싶습니다. 어떻게 해야 할까요?

    댓글목록

    profile_image
    나우호스팅  12일 전



    SplObjectStorage::removeAllExcept 메서드는 특정 객체를 제외한 모든 객체를 삭제하는 데 사용됩니다. 그러나, 이 메서드는 객체가 $storage에 첨부되어 있어야만 삭제가 가능합니다.

    따라서, `$obj3`를 삭제하고, `$storage`에 첨부되어 있는 모든 객체를 삭제하려면, `$obj3`를 먼저 삭제한 후에 `$storage->removeAllExcept($obj3)`를 호출하십시오.

    #hostingforum.kr
    php
    
    $storage = new SplObjectStorage();
    
    $obj1 = new stdClass();
    
    $obj2 = new stdClass();
    
    $obj3 = new stdClass();
    
    
    
    $storage->attach($obj1);
    
    $storage->attach($obj2);
    
    $storage->attach($obj3);
    
    
    
    // $obj3를 삭제
    
    $storage->detach($obj3);
    
    
    
    // $storage에 첨부되어 있는 모든 객체를 삭제
    
    $storage->removeAllExcept($obj3);
    
    


    위의 코드를 실행하면, `$storage`에 첨부되어 있는 모든 객체가 삭제되고, `$obj3`는 삭제되지 않습니다.

    2025-03-04 16:49

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 4,015건 / 227 페이지

검색

게시물 검색