Home > Backend Development > PHP Tutorial > PHP destructor and garbage collection mechanism

PHP destructor and garbage collection mechanism

WBOY
Release: 2016-07-25 08:53:50
Original
816 people have browsed it
  1. class person{
  2. public function __destruct() {
  3. echo "
    The destructor is executed here";
  4. echo "
    This is generally used Place, close the database, close the file, etc. finishing work ";
  5. }
  6. }
  7. $p = new person();
  8. for ($i = 0; $i < 5; $i++) {
  9. echo "< br /> $i";
  10. }
  11. //The object is destroyed before the php program ends.
  12. ?>
Copy code

When 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 "
    Generally used here To place, close the database, close the file, etc. ";
  5. }
  6. }
  7. $p = new person();
  8. $p = null;
  9. //We see here that the destructor is executed here. .
  10. for ($i = 0; $i < 5; $i++) {
  11. echo "
    $i";
  12. }
  13. ?>
Copy code

Set $p Assign $p a string if it is empty or on line 11, so that the object pointed to by $p becomes a garbage object. PHP will garbage destroy this object.

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 reference variable $p1 to also point to this object
  8. unset($p);
  9. echo "Do you see that /$p is destroyed and the object is also destroyed? What?";
  10. for ($i = 0; $i < 5; $i++) {
  11. echo "
    $i";
  12. }
  13. unset($p1);
  14. echo "We see Here, the destructor is executed";
  15. ?>
Copy code

When unset a reference variable, unset destroys the variable pointing to the object, not the object.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template