I
I
iplaton2019-03-10 23:55:12
PHP
iplaton, 2019-03-10 23:55:12

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

3 answer(s)
L
Lazy @BojackHorseman PHP, 2019-03-11
@iplaton

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.

M
Mysterion, 2019-03-11
@Mysterion

Why then the unset function

To free up memory and delete an object, e.g.
You are doing something wrong if you do not call the __destruct method when you try to delete an object using the unset function.
This class is probably called somewhere else.

A
artem78, 2019-03-11
@artem78

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()

https://ideone.com/Geaqs4
If you remove 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 question

Ask a Question

731 491 924 answers to any question