TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   When is __destruct() called? (http://www.talkphp.com/general/3126-when-__destruct-called.html)

Jenski 07-15-2008 10:34 AM

When is __destruct() called?
 
Hi,
I'm I've been programming in PHP4 for a few years now and am slowly moving over to PHP5, I was wondering when developing a class when the __destruct() function is called? I have put all my closing connections in it, and tried to print to screen for confirmation but it doesn't print anything.

Any thoughts?

Thanks in advance

Karl 07-15-2008 02:31 PM

It is called when you destroy the object. So, for example:

php Code:
class Destruct_Example
{
    public function __construct()
    {
        echo "Called Construct()";
    }
   
    public function __destruct()
    {
        echo "Called Destruct()";
    }
}

$pExample = new Destruct_Example();
unset($pExample);

And it will also be called at the end of the script.

Ross 07-15-2008 02:51 PM

It's quite useful in database abstraction classes, for example:

PHP Code:

abstract class Database
{
    public function 
__construct()
    {
        
$this->connect();
    }
    
    abstract public function 
connect();
    
/*...*/
    
    
public function __destruct()
    {
        
$this->conn->close();
    }


(although on second thoughts closing it on script exit isn't a huge memory saving :P).

xenon 07-15-2008 06:26 PM

The destructor is always called when the object is destroyed, set to null, or to another data type. If you don't do any of the above specified operations, the destructor will be automatically called after the script has ended (finished processing).

Jenski 08-04-2008 09:16 AM

Is it always called when the script has ended though?

Any reason why it doesn't?

xenon 08-04-2008 06:17 PM

Well, technically, no. The destructor is called when the script has ended, but the memory allocated for the object remains allocated until the garbage collector comes and wipes everything related to the php that's not used anymore. If you were asking if objects are persistent from one page to another, then no. Nothing in PHP is persistent, as all cgi modules use the HTTP protocol as a foundation to run on. And HTTP is a stateless protocol, as we all have learned.


All times are GMT. The time now is 11:35 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0