note 95123 added to class.splobjectstorage
| From: | randallgirard at hotmail dot com | Date: | Mon, 14 Dec 2009 20:01:35 +0000 |
| Subject: | note 95123 added to class.splobjectstorage | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-163959@lists.php.net to get a copy of this message | ||
I have two things to note about SplObjectStorage:
#1: A reference to the object itself is stored (not just a hash to compare against the object) and
it must be removed before the object is destroyed and the destructor is executed.
#2: SplObjectStorage::rewind() MUST be called to initiate the iterator and before
SplObjectStorage::current() will return an object (and I think the only way to retrieve an object?)
rather than automatically starting at the first element as I expected it to, like an array for
example. This assumption is based on SplObjectStorage::current() returning NULL until
SplObjectStorage::rewind() is called once the objects are contained. As a note, always use REWIND
before iterating through or fetching objects.
<?php
class foo {
public function __destruct() {
print("--- DESTRUCTOR FIRED!!<br />\r\n");
}
}
# Create object and storage
$bar = new foo();
$s = new SplObjectStorage();
# Rewind early just as a test
$s->rewind();
# attach the object
$s->attach($bar, array('test'));
# Unset the object; destructor does NOT fire
unset($bar);
print("Object has been unset<br />\r\n");
# First demonstrate that REWIND must be called to initialize the iterator
$obj = $s->current();
var_dump($obj);
print("- Note the NULL (from \$s->current())<br />\r\n");
# Initialize, and then detach the current (and only) object
$s->rewind();
$s->detach( $s->current() );
# The destructor should NOW execute
?>
Output:
Object has been unset
NULL - Note the NULL (from $s->current())
--- DESTRUCTOR FIRED!!
----
Server IP: 69.147.83.197
Probable Submitter: 76.167.60.11
----
Manual Page -- http://www.php.net/manual/en/class.splobjectstorage.php
Edit -- https://master.php.net/note/edit/95123
Del: integrated -- https://master.php.net/note/delete/95123/integrated
Del: useless -- https://master.php.net/note/delete/95123/useless
Del: bad code -- https://master.php.net/note/delete/95123/bad+code
Del: spam -- https://master.php.net/note/delete/95123/spam
Del: non-english -- https://master.php.net/note/delete/95123/non-english
Del: in docs -- https://master.php.net/note/delete/95123/in+docs
Del: other reasons-- https://master.php.net/note/delete/95123
Reject -- https://master.php.net/note/reject/95123
Search -- https://master.php.net/manage/user-notes.php