Home >Backend Development >PHP Tutorial >Two solutions for PHP destructor method __destruct() not triggering
This article mainly introduces two solutions to the problem that the PHP destructor method __destruct() is not triggered.
Sometimes when a class is referenced cyclically in PHP, it will cause the problem that __destruct() is not triggered. First, let’s look at the problem code:
<?php class Proxy { private $object; public function __construct($object) { $this->object = $object; } public function __destruct() { var_dump('__destruct:Proxy'); } } class Test { private $proxy; public function __construct() { $this->proxy = new Proxy($this); } public function __destruct() { var_dump('__destruct:Test'); } } $test = new Test; unset($test); echo 'no __destruct, wait 3s', PHP_EOL; sleep(3); echo '__destruct now:', PHP_EOL;
As shown in the above code, when running unset($test), __destruct() will not be triggered because there is a circular reference.
Look at the code of solution 1 below:
<?php class Proxy { private $object; public function __construct($object) { $this->object = $object; } public function __destruct() { var_dump('__destruct:Proxy'); } } class Test { private $proxy; public function __construct() { $this->proxy = new Proxy($this); } public function __destruct() { var_dump('__destruct:Test'); } public function close() { $this->proxy = null; } } $test = new Test; $test->close(); echo '__destruct now:', PHP_EOL; unset($test); sleep(3); echo 'no operation', PHP_EOL;
In the above code, before unset, set the proxy in the Test class to null, and then unset again to trigger __destruct ().
Of course, you can also manually gc (solution 2):
<?php class Proxy { private $object; public function __construct($object) { $this->object = $object; } public function __destruct() { var_dump('__destruct:Proxy'); } } class Test { private $proxy; public function __construct() { $this->proxy = new Proxy($this); } public function __destruct() { var_dump('__destruct:Test'); } } $test = new Test; unset($test); echo '__destruct now:', PHP_EOL; gc_collect_cycles(); sleep(3); echo 'no operation', PHP_EOL;
I hope it will be helpful to friends in need!
The above is the detailed content of Two solutions for PHP destructor method __destruct() not triggering. For more information, please follow other related articles on the PHP Chinese website!