首頁 >後端開發 >php教程 >PHP析構方法 __destruct() 不觸發的兩個解決方法

PHP析構方法 __destruct() 不觸發的兩個解決方法

藏色散人
藏色散人轉載
2019-04-24 11:22:373517瀏覽

本篇文章主要介紹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刪除