If there are recursive references to PHP objects, a memory leak will occur. This bug has existed in PHP for a long time. Let us reproduce this bug first. The code is as follows:
<?php class Foo { function __construct() { $this->bar = new Bar($this); } } class Bar { function __construct($foo) { $this->foo = $foo; } } for ($i = 0; $i < 100; $i++) { $obj = new Foo(); unset($obj); echo memory_get_usage(), " "; } ?>
Run the above code, you will find that the memory usage should remain unchanged, but in fact But it keeps increasing, and unset is not fully effective.
Many current developments are based on frameworks. There are complex object relationships in the application, so you are likely to encounter such problems. Let’s see what expedients can be done:
<?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 < 100; $i++) { $obj = new Foo(); $obj->__destruct(); unset($obj); echo memory_get_usage(), " "; } ?>
Fortunately, this bug has been fixed in the CVS code of PHP5.3.
Recursion termination conditions, generally there are many ways:
1. Add the recursion depth parameter to the parameters of the recursive function
The depth of each call Add one, add a conditional statement in the function body, and force a return when the depth exceeds a certain value;
2. Introduce the element stack structure, and some content that needs to be recorded in each recursion is usually pushed into the stack , pop up when appropriate
In the function body, add conditional statements to determine the stack size or stack elements, and return when the conditions are met;
The above is the detailed content of How to release recursive memory in php. For more information, please follow other related articles on the PHP Chinese website!