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.