Php destructor and garbage collection mechanism

Source: Internet
Author: User
Php destructor and garbage collection mechanism

  1. Class person {
  2. Public function _ destruct (){
  3. Echo"
    The Destructor is executed here ";
  4. Echo"
    It is generally used to place, close the database, close the file, and so on. ";
  5. }
  6. }
  7. $ P = new person ();
  8. For ($ I = 0; $ I <5; $ I ++ ){
  9. Echo"
    $ I ";
  10. }
  11. // The object is destroyed before the php program ends.
  12. ?>

If the object is not pointed to, the object is destroyed.

  1. Class person {
  2. Public function _ destruct (){
  3. Echo"
    The Destructor is executed here ";
  4. Echo"
    It is generally used to place, close the database, close the file, and so on. ";
  5. }
  6. }
  7. $ P = new person ();
  8. $ P = null;
  9. // We can see that the destructor is executed here.
  10. For ($ I = 0; $ I <5; $ I ++ ){
  11. Echo"
    $ I ";
  12. }
  13. ?>

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

  1. Class person {
  2. Public function _ destruct (){
  3. Echo"
    The Destructor is executed here.
    ";
  4. }
  5. }
  6. $ P = new person ();
  7. $ P1 = $ p; // set the new referenced variable $ p1 to also point to this object
  8. Unset ($ p );
  9. Echo "do you see/$ p is destroyed, and the object is also destroyed? ";
  10. For ($ I = 0; $ I <5; $ I ++ ){
  11. Echo"
    $ I ";
  12. }
  13. Unset ($ p1 );
  14. Echo "here, the destructor is executed ";
  15. ?>

When unset references a variable, unset destroys the variable pointing to the object, rather than the object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.