PHP: Don’t Call the Destructor Explicitly

“PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++”[1] says the documentation for destructors, but let’s see the following class.

class A
{
	public function __construct()
	{
		echo 'building an object';
	}
 
	public function __destruct()
	{
		echo 'destroying the object';
	}
}
 
$obj = new A();

Well, as you can not call the constructor explicitly:

$obj->__construct();

So we should not call the destructor explicitly:

$obj->__destruct();

The problem is that I’ve seen this many times, but it’s a pity that this won’t destroy the object and it is still a valid PHP code.

PHP destructors can't be called explicitly!
PHP destructors cannot be called explicitely!

Constructors and destructors in PHP are part of the so called magic methods. Here’s what the doc page says about them.

The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

To be more precise let’s take a look of the definition of destructors.

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

What if I Call the Destructor Explicitly?

Let’s see some examples!

class A
{
	public function __destruct()
	{
		echo 'destroying the object';
	}
}
 
$obj = new A();
 
// prints hello world
echo 'hello world';
 
// PHP interpreter stops the script execution and prints
// 'destroying the object'

This is actually a normal behavior. At the end of the script the interpreter frees the memory. Actually every object has a built-in destructor, just like it has built-in constructor. So even we don’t define it explicitly, the object has its destructor. Usually this destructor is executed at the end of the script, or whenever the object isn’t needed anymore. This can happen, for instance, at the end of a function body.

Now if we call the destructor explicitly, which as I said I’ve seen many times, here’s what happen.

class A
{
	public function __destruct()
	{
		echo 'destroying the object';
	}
}
 
$obj = new A();
 
// this is valid and it prints 'destroying the object'
// BUT IT DOES NOT DESTROY THE OBJECT
$obj->__destruct();
 
// prints hello world
echo 'hello world';
 
// HERE PHP ACTUALLY DESTROYS THE $obj OBJECT
// ... and again prints 'destroying the object'

As you can see calling the destructor explicitly doesn’t destroy the object. So the question is …

How to Destroy an Object Before the Script Stops?

Well, to destroy an object you can assign a NULL value to it.

class A
{
	public function __destruct()
	{
		echo 'destroying the object';
	}
}
 
$obj = new A();
 
// prints 'destroying the object'
$obj = null;
 
// prints 'hello world'
echo 'hello world';
 
// the script stop its execution

Caution

Be aware of that if you don’t clone the object $obj, and simply assign it to another variable, then $obj = null will be pointless. Let’s see the following example.

class A 
{
	public function printMsg()
	{
		echo 'I still exist';
	}
 
	public function __destruct()
	{
		echo 'destroying the object';
	}
 
}
 
$obj = new A();
 
// $newObj is pointing to $obj
$newObj = $obj;
 
// this doesn't destroy $newObj
// as it appears both $obj and $newObj point to the same memory
// so PHP doesn't free this memory
$obj = null;
 
// prints 'i still exist'
$newObj->printMsg();
 
// prints 'hello world'
echo 'hello world';
 
// now the scripts destroys the "object", which in this
// case is $newObj and prints 'destroying the object'

This example shows us that actually by assigning NULL to an object doesn’t quite destroy it if there are another objects pointing to the same memory.

class A 
{
	public function printMsg()
	{
		echo 'I still exist';
	}
 
	public function __destruct()
	{
		echo 'destroying the object';
	}
 
}
 
$b = new A();
 
$d = $c = $b;
 
$b = null;
 
$c->printMsg();
$d->printMsg();
 
// prints 'destroying the object' ONLY ONCE

In this last example there are two interesting things to note. First $b = null doesn’t call the destructor, and at the end of the script there’s only one implicit call of the destructor, although there are two objects.

Conclusion

The important thing to note is that you shouldn’t call the destructor of an object explicitly! Not because it will throw an fatal error, but simply because it won’t destroy the object.

[1] PHP: Constructors and Destructors

8 thoughts on “PHP: Don’t Call the Destructor Explicitly

  1. Just pointing out in your first examples that you spelled ‘funciton’ wrong. Interesting read though; though instead of setting $obj to null, I’d look more into using unset();

  2. For the destructor not “killing” a object, you and most others got it wrong. It is normal, and it is the way it should behave. A destructor is what you would normally call a hook, that gets called before the object is actually destroyed, allowing you to do additional operations either before nulling a object or the script shutting down.

    Also please beware that destroying a object will not actually destroy the object because an object can be destroyed only when there are no references to it anymore. Since in php5 all assignments of objects are done by reference, if $x is a object, $a = $x, $x = NULL, will only eliminate the variable $x, because $a still holds a valid reference to the initial object.

  3. Hi Cristian,

    it seems like you haven’t read the post. An excerpt from one of the examples clearly explains yours “… if $x is a object, $a = $x, $x = NULL, will only eliminate the variable $x, because $a still holds a valid reference to the initial object.”

    $obj = new A();
     
    // $newObj is pointing to $obj
    $newObj = $obj;
     
    // this doesn't destroy $newObj
    // as it appears both $obj and $newObj point to the same memory
    // so PHP doesn't free this memory
    $obj = null;
  4. Yes. But you missed a small thing in PHP 5 [actually a big one]. All object assignments ARE DONE by reference. So $tsttsts = $obj means that $tsttsts is a reference to the same memory block. :) i am sorry if i was unclear [i assumed this was already pointed out]. In PHP5 there is the cloning for getting a clone of the object.

    I am sorry and i hope i haven’t offended you with this response.

    Thanks for the response, Cristian.

  5. Just saw that you have a article about passing by reference, so the entire $x = NULL discussion is [i think] on a no-subject. As long as you still have a reference to your object, the object cannot be destroied :)

  6. I havnt understood the last example
    How this

    $b = new A();
    $d = $c = $b;

    is different from

    $obj = new A();
    $newObj = $obj;

  7. I can see one scenario where calling __destruct directly is useful, or required, and that is in unit testing…. just a thought..

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>