Today I have read a question what is difference between final, finally and finalize ?
Final is a keyword. Finally is a block.
Final Keyword
Variable - If you make any variable as final, you cannot change the value of final variable(It will be constant).
Method - If you make any method as final, you cannot override it.
Class - If you make any class as final, you cannot extend it
Finally Block
Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.
What is finalize,Is it possible with PHP? If yes, then How?
Finalize is an object method that contains the code required to free unmanaged resources and perform cleanup operations prior to garbage collection.
In Java, the java.lang.Object.finalize()
is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize
method to dispose of system resources or to perform other cleanup.
PHP does not contain a finalize()
method. Rather, you can use the __destruct
magic method if you need to free resources or connections from memory when an object is collected by the GC. Specifically, from the documentation:
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.
It is also worth noting that with PHP (unlike the finalize
method in Java, for example) throwing a new exception in the destructor will cause issues:
Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.