Circular Reference cleanup
| From: | Chris Monson | Date: | Mon, 10 Jul 2000 17:25:21 +0000 |
| Subject: | Circular Reference cleanup | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-5761@lists.php.net to get a copy of this message | ||
Since PHP is a reference counted language, it has trouble with circular
references (of course). Now that PHP 4 supports references to
variables, it is possible to create structures that were difficult or
impossible to represent before, like n-trees, etc.
I have created such a structure, where each node in the tree has as one
of its memebers a reference to its parent node. This is very useful for
reverse traversal, and it would be painful (possible, but painful) to
have to get rid of the parent references in each node.
The reason that having a reference to a parent node from a child node is
a problem is this: PHP is reference counted. That means that data
elements that have circular references like this will not be destroyed
until the script exits, at which point the Zend code dumps out a bunch
of memory leak information.
There are a few ways of addressing this issue:
1) Implement true garbage collection (likely not an option)
2) Allow for "soft" references (allow a reference variable to exist
without incrementing the reference count, thus allowing an object to be
destroyed even though other variables refer to it)
3) Have a destructor in PHP that allows the class creator to go and
clean up the circular references when some container object is destroyed.
The first option is probably not an option at all, so I won't bother
addressing it here.
The second is actually very appealing, in that it would allow for self-
referential data structures and it would simultaneously allow reference
counting to work. The downside is that it would require a special sort
of syntax to differentiate between reference types, and it would confuse
the issue of references just a bit.
The third is my favorite because it seems that it should be easy to
implement some sort of destructor mechanism in PHP without breaking the
existing code and without confusing the language with obscure features
like soft references. It has always been a bit disturbing to me that
there is no (documented) destructor mechanism for PHP objects. Even if
PHP is great at cleaning stuff up, it is very nice to have a destructor
mechanism so that file handles, queries, and contained self-referential
structures can be cleaned up.
At any rate, if anyone knows of a destructor mechanism in PHP that has
simply not been documented yet, please let me know. Otherwise, let's
discuss this shortcoming in PHP and see if there are other solutions or
workarounds.
Chris