Php destructor and garbage collection mechanism
- Class person {
- Public function _ destruct (){
- Echo"
The Destructor is executed here ";
- Echo"
It is generally used to place, close the database, close the file, and so on. ";
- }
- }
- $ P = new person ();
- For ($ I = 0; $ I <5; $ I ++ ){
- Echo"
$ I ";
- }
- // The object is destroyed before the php program ends.
- ?>
If the object is not pointed to, the object is destroyed.
- Class person {
- Public function _ destruct (){
- Echo"
The Destructor is executed here ";
- Echo"
It is generally used to place, close the database, close the file, and so on. ";
- }
- }
- $ P = new person ();
- $ P = null;
- // We can see that the destructor is executed here.
- For ($ I = 0; $ I <5; $ I ++ ){
- Echo"
$ I ";
- }
- ?>
If $ p is set to null or 11th rows, $ p is assigned a string, so that the object pointed to before $ p becomes a junk object. Php destroys the object garbage.
Unset variable
- Class person {
- Public function _ destruct (){
- Echo"
The Destructor is executed here.
";
- }
- }
- $ P = new person ();
- $ P1 = $ p; // set the new referenced variable $ p1 to also point to this object
- Unset ($ p );
- Echo "do you see/$ p is destroyed, and the object is also destroyed? ";
- For ($ I = 0; $ I <5; $ I ++ ){
- Echo"
$ I ";
- }
- Unset ($ p1 );
- Echo "here, the destructor is executed ";
- ?>
When unset references a variable, unset destroys the variable pointing to the object, rather than the object. |