destructor: executes when an object becomes garbage or when an object is explicitly destroyed.
GC (Garbage Collector)
In PHP, when no variable points to this object, the object becomes garbage. PHP will destroy it in memory.
This is the PHP gc (garbage Collector) garbage disposal mechanism to prevent memory overflow.
When a PHP thread ends, all memory space currently occupied is destroyed, and all objects in the current program are also destroyed.
__destruct () destructor
a __destruct () destructor that executes when a garbage object is reclaimed.
Destructors can also be called explicitly, but do not do so.
Destructors are called automatically by the system and do not call a fictitious function of an object in a program.
destructors cannot have parameters.
As shown in the following procedure, all objects are destroyed before the program ends. The destructor was called.
Copy Code code as follows:
?
Class Person {
Public Function __destruct () {
The Echo ' destructor now executes the <br/> ';
Echo ' Here is generally used to set up, close the database, close the file and so on finishing work ';
}
}
$p = new Person ();
for ($i = 0; $i < 5; $i + +) {
echo "$i <br/>";
}
?>
program Run Result:
0
1
2
3
4
The destructor now executes the
This is generally used to set up, close the database, close the file and so on finishing work
The object is destroyed when the object does not point to it.
Copy Code code as follows:
?
Class Person {
Public Function __destruct () {
The Echo ' destructor now executes the <br/> ';
}
}
$p = new Person ();
$p = null; The destructor here executes the
$p = "ABC"; The same effect
for ($i = 0; $i < 5; $i + +) {
echo "$i <br/>";
}
?>
program Run Result:
The destructor now executes the
0
1
2
3
4
In line 10th above, we set the $p to null or line 11th to give $p a string so that the object that $p pointed to is a garbage object. PHP destroys this object's garbage.
PHP unset variables
Copy Code code as follows:
?
Class Person {
Public Function __destruct () {
The Echo ' destructor now executes the <br/> ';
}
}
$p = new Person ();
$p 1 = $p;
Unset ($p);
Echo ' Now destroys $p, and has the object been destroyed? <br/> ';
for ($i = 0; $i < 5; $i + +) {
echo "$i <br/>";
}
Echo ' Now destroys $p 1, that is, there are no variables pointing to the object <br/> ';
Unset ($p 1); Now there is no variable to point to the object, and the destructor here executes the
?>
program Run Result:
Now that the $p has been destroyed, has the object been destroyed?
0
1
2
3
4
Now $p 1 is destroyed, that is, there are no variables to the object.
The destructor now executes the
Unset destroys a variable that points to an object, not the object.