Java has no destructor but has finishers and other mechanisms more modern and considered better. In fact the destructor was created more to finalize something, so the term is bad. Do not understand this method as something that destroys the object but something that does something before it is destroyed.
So if you understand the concept of Java resource completion/closure you know how __destruct
PHP. If you don’t understand, I hope you’ll only do simple things.
PHP has GC yes, just isn’t the same as Java. Have you ever needed to free up memory? It’s a problem if you don’t create destructor in most cases?
To tell the truth in 99% of the cases where PHP is used, neither GC nor destructor is very necessary. In fact there is a lot of class that I see around that strictly speaking should have a constructor and it doesn’t have, even so it doesn’t cause problems because PHP is a language of script.
Since PHP’s GC is deterministic it works the same as C++, so once the object is no longer needed and has no references to it, the destructor is already called.
In Java another mechanism is needed since the release of the object is not deterministic and may even never be called by the GC. It uses the so-called try-resource
that finalizes the object so it is no longer necessary. And if it’s used as a member of an object, it practically forces you to have a finalizer in the object that contains it. In the destruction by the GC the finalizer is only called if he has not been called before.
Because of the determinism of PHP the destructor is much simpler.
You should use a destructor whenever you have some feature that needs a finish, IE, you need to close a connection, a file, etc. But as I said, no one does it and in PHP it gives in the same in almost all cases.
Destructor runs whenever object is no longer used by code.
The closing or reloading of a page does not interfere with this, since the page is in the client and PHP is in the server, are completely separate things, using another technology. The end of script that generates the page or does something else will surely call the destructor if nothing catastrophic doesn’t happen before.
If the script is called again every memory environment of the previous no longer exists and everything will be created again. And that’s why the destructor doesn’t make much difference in PHP, although conceptually it should always exist.
Have any answers solved what was in doubt? Do you need something else to be improved? Do you think it is possible to accept it now?
– Maniero
Related: The method
__destruct
has use?– Guilherme Nascimento