PHP SplObjectStorage detach() Function
Last Updated :
23 Jun, 2023
Improve
The SplObjectStorage::detach() function is an inbuilt function in PHP which is used to remove objects from the storage.
Syntax:
php
php
void SplObjectStorage::detach($obj)Parameters: This function accepts a single parameter $obj which specifies the object to be remove from the storage. Return Value: This function does not return any value. Below programs illustrate the SplObjectStorage::detach() function in PHP: Program 1:
<?php
// Creating class
$obj = new StdClass;
// Create an empty storage class
$str = new SplObjectStorage();
// Add some object
$str->attach($obj, "GeeksforGeeks");
// Print result before detaching
var_dump(count($str));
// Detaching object
$str->detach($obj);
// Print result after detach
var_dump(count($str));
?>
<?php
// Creating class
$obj = new StdClass;
// Create an empty storage class
$str = new SplObjectStorage();
// Add some object
$str->attach($obj, "GeeksforGeeks");
// Print result before detaching
var_dump(count($str));
// Detaching object
$str->detach($obj);
// Print result after detach
var_dump(count($str));
?>
Output:
Program 2:
int(1) int(0)
<?php
// Creating class
$obj1 = new StdClass;
$obj2 = new StdClass;
$obj3 = new StdClass;
// Create an empty storage class
$str = new SplObjectStorage();
// Add some object
$str->attach($obj1, "GeeksforGeeks");
$str->attach($obj2);
$str->attach($obj3, "GFG");
// Print result before detaching
var_dump(count($str));
// Detaching object
$str->detach($obj1);
// Print result after detach first object
var_dump(count($str));
// Detaching object
$str->detach($obj3);
// Print result after detach second object
var_dump(count($str));
?>
<?php
// Creating class
$obj1 = new StdClass;
$obj2 = new StdClass;
$obj3 = new StdClass;
// Create an empty storage class
$str = new SplObjectStorage();
// Add some object
$str->attach($obj1, "GeeksforGeeks");
$str->attach($obj2);
$str->attach($obj3, "GFG");
// Print result before detaching
var_dump(count($str));
// Detaching object
$str->detach($obj1);
// Print result after detach first object
var_dump(count($str));
// Detaching object
$str->detach($obj3);
// Print result after detach second object
var_dump(count($str));
?>
Output:
Reference: https://www.php.net/manual/en/splobjectstorage.detach.php
int(3) int(2) int(1)