Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How reliable is __destruct?

Tags:

arrays

php

Are there situations in which this method would not be called?

I'm thinking to store a important variable into a persistent cache just before the cache object gets destroyed. This variable is used many times in the page so I wouldn't like to update the cache with it every time the variable changes...

like image 282
Alex Avatar asked Feb 05 '12 20:02

Alex


People also ask

What is__ destruct in PHP?

PHP - The __destruct FunctionA destructor is called when the object is destructed or the script is stopped or exited. If you create a __destruct() function, PHP will automatically call this function at the end of the script. Notice that the destruct function starts with two underscores (__)!

What are the__ construct() and__ destruct() methods in a PHP class?

Example# __construct() is the most common magic method in PHP, because it is used to set up a class when it is initialized. The opposite of the __construct() method is the __destruct() method. This method is called when there are no more references to an object that you created or when you force its deletion.


3 Answers

Let's have a class:

class A {
    public function __construct(){
        echo "Construct\n";
    }

    public function __destruct(){
        echo "Destruct\n";
    }
}

And test code:

$test = new A();
die( "Dead\n");  // Will output Construct; dead; Destruct

$test = new A();
throw new Exception("Blah\n"); // Construct, Fatal error (no destruct)

$test = new A();
require_once( 'invalid_file.php'); // Construct, Fatal error (no destruct)

So basically: there are situations (fatal errors) when destructor won't be called.

Ah and this question has the same answer as this one: When will __destruct not be called in PHP? (+/-)

like image 119
Vyktor Avatar answered Oct 18 '22 02:10

Vyktor


It is called as soon as there are no more references to that particular object, or during the shutdown sequence. The manual also states destructors are called when scripts are terminated with exit().

Aside from the issue pointed out by TimWolla, I am not aware of any problems with PHP destructors.

like image 3
drew010 Avatar answered Oct 18 '22 01:10

drew010


It seems there at least was a problem using Windows: https://github.com/WoltLab/WCF/blob/ff7e6ed381f2ccab7f51220f97087921133b2237/wcfsetup/install/files/lib/system/WCF.class.php#L122

I don't know whether this is still relevant.

like image 1
TimWolla Avatar answered Oct 18 '22 03:10

TimWolla