Home >Backend Development >PHP Problem >The role of php destructor

The role of php destructor

藏色散人
藏色散人Original
2019-08-24 13:58:264031browse

The role of php destructor

The role of the php destructor

In short, the role of the destructor is to release memory.

Destructor

__destruct ( void ) : void

PHP 5 introduced the concept of destructor, which is similar to other object-oriented languages ​​such as C. The destructor is executed when all references to an object are deleted or when the object is explicitly destroyed, which means that the destructor is executed when the object instantiated by the class is destroyed.

Destructor example

<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }
   function __destruct() {
       print "Destroying " . $this->name . "\n";
   }
}
$obj = new MyDestructableClass();
?>

Like the constructor, the destructor of the parent class will not be called secretly by the engine. To execute the parent class's destructor, parent::__destruct() must be explicitly called in the child class's destructor body. In addition, just like the constructor, the subclass will inherit the parent class if it does not define a destructor.

The destructor is called even when the script is terminated using exit(). Calling exit() in the destructor will abort the remaining shutdown operations.

Note:

● The destructor is called when the script is closed, when all HTTP headers have been sent. It is possible that the working directory when the script is closed is different from when it is in a SAPI (such as apache).

● Attempting to throw an exception in the destructor (which is called when the script terminates) will result in a fatal error.

Related recommendations: [PHP Tutorial]

The above is the detailed content of The role of php destructor. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn