Should we always unset a class as soon as possible if we want to use complex code in __destruct?

I have the following problem. I'm using a class and I want to do some 'event saving (and logging)' in the __destructor method, i need to be sure that my database class is still active, and even that my memcache class is still active.

I noticed that the destructor method can be called way too late. (database class no longer active, memcache class no longer active)

A workaround i have found is...

$forum = new Forum_class();
$forum->output();
unset($forum) <-- unset it

Is this a good practice? Or should i just skip using the destructor method to do stuff that relies on other classes being active... (available database class, available memcache class...)

I most likely shouldn't unset my database and memcache class as soon as possible but for the other classes, should you unset them as soon as possible. (when they are not needed on the page anymore) Or only if you want to use the __destructor function?

Or am i doing something horrible wrong? It just seems weird to always have to make sure you unset a class. If i forget it once, my __destructor method can produce errors...

Edit: i think i stumbled upon this bug https://bugs.php.net/bug.php?id=39381. My database class and memcache class use globals...

Answers


You are doing it right. But...

The destructor MIGHT be called after the last link to the object is destroyed. Even unset($object) does not guarantee that the destructor is called immediately after unset().

$forum = new Forum_class();
$forum->output();
$forumCopy = $forum;
unset($forum); // php doesnt even consider calling the destructor
unset($forumCopy); // now the destructor is going to be called... in some time

Or should i just skip using the destructor method to do stuff that relies on other classes being active...

Basically, although you can try a hybrid approach:

class Foo
{
  protected $resource;

  public function close()
  {
    if ($this->resource)
    {
      $this->resource->foo();
      $this->resource = null;
    }  
  }

  public function __destruct()
  {
    $this->close();
  }
}

This way you can explicitly "close" your resource, but also lazily do it via the destructor just in case.

If the cleanup (the close() method) is critical, then I'd change the __destruct method to log to a file (e.g., trigger a notice) if it wasn't cleaned up. That way you could easily find and correct those issues.


Need Your Help

PLSQL: mutating table stopping my 'before update trigger'. What to do?

plsql triggers mutating-table

I've finally compiled my trigger , but now I'm getting a mutating table error when I do the relevant update:

Can I validate the <marquee>?

html validation onmouseover marquee

Is there a way to validate the tag? And I have two elements with OnMouseOver attribute, and the validator, too don't validate them. The only errors are these. So if you know a way, please share...