The SplObjectStorage::attach() function is an inbuilt function in PHP which is used to add objects into the SplObjectStorage.
Syntax:
void SplObjectStorage::attach($obj, $val)
Parameters: This function accepts two parameters as mention above and described below.
- $obj: This is required parameter which specifies the object of the storage class.
- $val: This is an optional parameter which specified the values to be added.
Return Value: This function does not returns any value.
Below programs illustrate the SplObjectStorage::attach() function in PHP:
Program 1:
<?php // Declare new object $obj = new StdClass; // Create an empty storage class $str = new SplObjectStorage(); // Attach $obj with String "GeeksforGeeks" $str->attach($obj, "GeeksforGeeks"); // Print Result var_dump($str[$obj]); ?> |
string(13) "GeeksforGeeks"
Program 2:
<?php // Creating std classes $obj1 = new StdClass; $obj2 = new StdClass; $obj3 = new StdClass; $obj4 = new StdClass; $str = new SplObjectStorage(); $str->attach($obj1); $str->attach($obj2, "GFG"); // Another way to use attach() function $str[$obj3] = "GeeksforGeeks"; $str[$obj4] = NULL ; // Print Result var_dump($str[$obj1]); var_dump($str[$obj2]); var_dump($str[$obj3]); var_dump($str[$obj4]); ?> |
NULL string(3) "GFG" string(13) "GeeksforGeeks" NULL
Reference: https://www.php.net/manual/en/splobjectstorage.attach.php
Recommended Posts:
- How to attach file with feedback form in PHP ?
- PHP | SplObjectStorage contains() Function
- PHP | SplObjectStorage count() Function
- PHP | SplObjectStorage addAll() Function
- PHP | SplObjectStorage valid() Function
- PHP | SplObjectStorage current() Function
- PHP | SplObjectStorage next() Function
- PHP | SplObjectStorage detach() Function
- PHP | SplObjectStorage getinfo() Function
- PHP | SplObjectStorage key() Function
- PHP | SplObjectStorage offsetSet() Function
- PHP | SplObjectStorage offsetExists() Function
- PHP | SplObjectStorage offsetGet() Function
- PHP | SplObjectStorage offsetUnset() Function
- PHP | SplObjectStorage removeAll() Function
- PHP | SplObjectStorage removeAllExcept() Function
- PHP | SplObjectStorage rewind() Function
- PHP | SplObjectStorage serialize() Function
- PHP | SplObjectStorage setInfo() Function
- PHP | SplObjectStorage unserialize() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

