PHP Memory Leak Issue

Oct 12, 2013, by admin

When processing a large number of records or calling objects with recursive references, a memory leak can occur causing PHP to run out of memory. PHP 5.3 has a garbage collector gc_enable() that can collect cyclic references. You can also avoid the memory leak issue by manually calling the destructors and unsetting the recursive ref like below.

  1. <?php
  2. class A {
  3. function __construct () {
  4. $this->b = new B($this);
  5. }
  6. function __destruct () {
  7. $this->b->__destruct();
  8. }
  9. }
  10. class B {
  11. function __construct ($parent = NULL) {
  12. $this->parent = $parent;
  13. }
  14. function __destruct () {
  15. unset($this->parent);
  16. }
  17. }
  18. for ($i = 0 ; $i < 5000000 ; $i++) {
  19. $a = new A();
  20. $a->__destruct();
  21. }
  22. echo number_format(memory_get_usage());
  23. ?>

Also Memory leak issue can occur due to server configuration, so make sure to check it at server end.