Home > Article > Backend Development > When is the php destructor called?
When the destructor is called
The destructor is called in the following 3 situations:
When the object life cycle ends and is destroyed;
Actively call delete; (Recommended learning: PHP programming from entry to proficiency)
Object i is As a member of object o, when the destructor of o is called, the destructor of object i is also called.
PHP 5 introduced the concept of destructors, 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.
<?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 will be called even when exit() is used to terminate the script execution. Calling exit() in the destructor will abort the rest of the shutdown operation.
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 When is the php destructor called?. For more information, please follow other related articles on the PHP Chinese website!