php destructor behaviour

前端 未结 5 1668
一个人的身影
一个人的身影 2020-12-16 00:23

im trying to understand php constructor and destructor behaviour. Everything goes as expected with the constructor but i am having trouble getting the destructor to fire imp

5条回答
  •  情话喂你
    2020-12-16 01:00

    The __destruct method of a class is called once all references to the object are unset.

    For example

    $dummy = (object) new Class();
    

    The destructor is automatically called if the dummy object is set to null or the script is exited.

    unset($dummy); // or $dummy = null;
    //exit(); //also possible
    

    However, there are three crucial memory notes to calling the destructor method:

    Firstly, the desctructor method should be a public method, not protected or private.

    Secondly, refrain from using internal and circular references. For example:

    class NewDemo
    {
         function __construct()
         {
              $this->foo = $this;
         } 
         function __destruct()
         {
              // this method will never be called 
              // and cause memory leaks
              // unset will not clear the internal reference
         }
    }
    

    The following will not work either:

    $a = new Class();
    $b = new Class();
    $a->pointer = $b;
    $b->pointer = $a;
    
    unset($a); // will not call destructor
    unset($b); // will not call destructor
    

    Thirdly, deciding whether destructors are called after output is sent. Using

    gc_collect_cycles() 
    

    one can determine whether all destructors are called before sending data to user.

    See http://php.net/manual/en/language.oop5.decon.php for the sources and elaborate explanations of magic destruct methods with examples.

提交回复
热议问题