PHP Object Recursive reference causes memory leak analysis _php tips

Source: Internet
Author: User
Tags memory usage

Typically, a memory leak occurs if the PHP object has a recursive reference. This bug has been in PHP for a long time, so let's reproduce the bug, with the sample code as follows:

<?php
class Foo {
  function __construct () {
    $this->bar = new Bar ($this);
  }
}

Class Bar {
  function __construct ($foo) {
    $this->foo = $foo;
  }
}

for ($i = 0; $i < $i + +) {
  $obj = new Foo ();

  Unset ($obj);
  Echo memory_get_usage (), "/n";
}
? > 

Run the above code, you will find that memory usage should be the same, but in fact it is constantly increasing, unset not fully effective.

Now many of the development is based on the framework, the application of complex object relationships, then it is likely to encounter such a problem, the following to see what the expedient:

<?php
class Foo {
  function __construct () {
    $this->bar = new Bar ($this);
  }

  function __destruct () {
    unset ($this->bar);
  }

Class Bar {
  function __construct ($foo) {
    $this->foo = $foo;
  }
}

for ($i = 0; $i < $i + +) {
  $obj = new Foo ();

  $obj->__destruct ();
  Unset ($obj);
  Echo memory_get_usage (), "/n";
}
? >

It was a little ugly, but finally it was over. Fortunately, the bug has been fixed in PHP5.3 's CVS code .

In this regard, in the PHP design, it is necessary to pay attention to! I believe this article on the PHP program design has a certain reference value.

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.