Home >Backend Development >PHP Problem >what is destructor in php
Destructor
__destruct ( void ) : void
PHP 5 introduced the concept of destructor, which is similar to other object-oriented languages. Such as C. A destructor is executed when all references to an object are removed or when the object is explicitly destroyed.
The destructor will be executed when all references to an object are deleted (whether explicitly destroyed or implicitly destroyed) or when the php file is executed.
All references to an object are deleted: (Recommended learning: PHP programming from beginner to proficient)
、使用unset(对象名),将对象名销毁 2、$对象名 = null 3、$对象名 = 'abc'
Explicit Destruction:
The three methods written above are all explicit destruction. The so-called explicit destruction means that the programmer actively deletes the object reference.
If the programmer does not explicitly destroy the object, then after the program is executed, the object will be destroyed by the system. This is system destruction. Also called implicit destruction.
Basic syntax:
class 类名{ public function __destruct(){ //函数体 //析构函数的重要作用,就是释放对象创建的资源 //比如 数据库连接,文件句柄,绘图句柄。。。 } }
Description:
(1) Destructors are all public
(2) __destruct is a keyword, do not modify
(3) The destructor has no formal parameters
(4) The system calls
during the destructor (5 ) The destructor will be called by the system in the following situations
The php file is executed
It will be executed when all references to an object are deleted or when the object is explicitly destroyed.
<?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, after 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).
Note:
Attempting to throw an exception in the destructor (which is called when the script terminates) will result in a fatal error.
The above is the detailed content of what is destructor in php. For more information, please follow other related articles on the PHP Chinese website!