Re: Pre-Destructor magic function?

From: Date: Sun, 12 Aug 2007 19:58:04 +0000
Subject: Re: Pre-Destructor magic function?
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-31540@lists.php.net to get a copy of this message
Hi Richard, class A { public $bs = array(); function addB() {
    $this->bs[] = new B($this);
} } class B { public $parent; function __construct($parent) {
    $this->parent = $parent;
} } function doSomething() { $a = new A(); $a->addB(); $a->addB(); } See the problem? The object $a isn't available from global space, but because of the circular reference, A and all its Bs won't be picked up by the garbage collector. Have this 22 000 times and you run out of memory. Best regards, Arnold Richard Lynch wrote:
On Fri, August 10, 2007 6:01 pm, Nathanael D. Noblet wrote: I'm not a PHP OOP expert, so this could be 100% wrong, but...
$obj = new A(); in a loop the object's never released from memory because of the internal references it holds. __destruct is not called until the end of script execution etc. Now normally in a web request
    
If __destruct isn't being called until the end of the script, then PHP thinks you still have some way of accessing that object, and it can't free it.
situation this isn't a big deal. However I'm using it in a batch and loop over 22 000 records. Since re-assigning the single object I use isn't freeing any memory it consumes quite a bit.
    
Perhaps set some things to NULL or unset them explicitly to convince PHP that you are done with them.
I have gotten around it by creating a special function in the object to manually release the recursive references.
    
Well, there you go. Release the references so PHP knows you are done with them.
However it would be nice if there were some sort of 'magic' function that could be called on an object so that it knows it is being deleted, sort of like a __preDestruct or something like that... Is that a bad idea? Or I guess better able to handle recursive references in objects would be the other way to solve it I guess.
    
__destruct is called right before PHP destroys the object. There really isn't any event of any significance for a __perDesctruct... Either you're done with it, or you're not...


« previous php.internals (#31540) next »