首页 >后端开发 >php教程 >PHP析构方法 __destruct() 不触发的两个解决办法

PHP析构方法 __destruct() 不触发的两个解决办法

藏色散人
藏色散人转载
2019-04-24 11:22:373535浏览

本篇文章主要给大家介绍PHP 析构方法 __destruct() 不触发的两个解决办法。

有时候在 PHP 里类循环引用时,会导致 __destruct() 不触发的问题,先上问题代码:

<?php
class Proxy
{
    private $object;
 
    public function __construct($object)
    {
        $this->object = $object;
    }
 
    public function __destruct()
    {
        var_dump(&#39;__destruct:Proxy&#39;);
    }
}
 
class Test
{
    private $proxy;
 
    public function __construct()
    {
        $this->proxy = new Proxy($this);
    }
 
    public function __destruct()
    {
        var_dump(&#39;__destruct:Test&#39;);
    }
}
 
$test = new Test;
unset($test);
 
echo &#39;no __destruct, wait 3s&#39;, PHP_EOL;
 
sleep(3);
 
echo &#39;__destruct now:&#39;, PHP_EOL;

如上代码,运行unset($test)时,不会触发__destruct(),因为有了循环引用。

再看下面的解决方法1的代码:

<?php
class Proxy
{
    private $object;
 
    public function __construct($object)
    {
        $this->object = $object;
    }
 
    public function __destruct()
    {
        var_dump(&#39;__destruct:Proxy&#39;);
    }
}
 
class Test
{
    private $proxy;
 
    public function __construct()
    {
        $this->proxy = new Proxy($this);
    }
 
    public function __destruct()
    {
        var_dump(&#39;__destruct:Test&#39;);
    }
 
    public function close()
    {
        $this->proxy = null;
    }
}
 
$test = new Test;
$test->close();
 
echo &#39;__destruct now:&#39;, PHP_EOL;
 
unset($test);
 
sleep(3);
 
echo &#39;no operation&#39;, PHP_EOL;

上面的代码,在unset之前,将Test类中的proxy设为null,然后再unset,就可以触发__destruct()了。

当然,你也可以手动gc(解决方法2):

<?php
class Proxy
{
    private $object;
 
    public function __construct($object)
    {
        $this->object = $object;
    }
 
    public function __destruct()
    {
        var_dump(&#39;__destruct:Proxy&#39;);
    }
}
 
class Test
{
    private $proxy;
 
    public function __construct()
    {
        $this->proxy = new Proxy($this);
    }
 
    public function __destruct()
    {
        var_dump(&#39;__destruct:Test&#39;);
    }
}
 
$test = new Test;
unset($test);
 
echo &#39;__destruct now:&#39;, PHP_EOL;
gc_collect_cycles();
 
sleep(3);
 
echo &#39;no operation&#39;, PHP_EOL;

希望对需要的朋友有所帮助!

以上是PHP析构方法 __destruct() 不触发的两个解决办法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:yurunsoft.com。如有侵权,请联系admin@php.cn删除