Answer the question
In order to leave comments, you need to log in
Why isn't the destructor of an object called when it's deleted with unset?
For a long time I could not understand why some garbage in the logic of the program is happening. Found out that the destructor is called at the final completion of the script. I understand of course, the garbage collector is smarter than everyone else and knows better than the code programmer how to delete objects. Why then the unset function?
Answer the question
In order to leave comments, you need to log in
And this is not a destructor in fact, but a finalizer. So it goes.
and unset is needed for what it is intended for. get rid of the reference to the variable. when there are zero references to a variable, it goes to the garbage collector. Well, the programmer does not control the time when the garbage collector calls the finalizer of the object.
Why then the unset function
And what about the garbage collector? The function unset()
marks the variable as no longer used, which entails calling the object's destructor.
The following code behaves exactly as it is supposed to:
<?php
class Foo {
function __construct() {
print("Object created\n");
}
function __destruct() {
print("Object destroyed\n");
}
}
$foo = new Foo();
print("Before unset()\n");
unset($foo);
print("After unset()\n");
Object created
Before unset()
Object destroyed
After unset()
unset()
the destructor, it will be called when the variable goes out of scope (that is, in this example, when the script ends).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question