旗下导航:搜·么
当前位置:网站首页 > PHP教程 > 正文

PHP析构要领 __destruct() 不触发的两个解决办法【php教程】

作者:搜搜PHP网发布时间:2019-12-01分类:PHP教程浏览:70


导读:本篇文章主要给人人引见PHP析构要领__destruct()不触发的两个解决办法。有时候在PHP里类轮回援用时,会致使__destruct()不触发的题目,先...
本篇文章主要给人人引见PHP 析构要领 __destruct() 不触发的两个解决办法。

有时候在 PHP 里类轮回援用时,会致使 __destruct() 不触发的题目,先上题目代码:

<?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;

如上代码,运转unset($test)时,不会触发__destruct(),由于有了轮回援用。

再看下面的解决要领1的代码:

<?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;

上面的代码,在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('__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;

愿望对须要的朋侪有所协助!

以上就是PHP析构要领 __destruct() 不触发的两个解决办法的细致内容,更多请关注ki4网别的相干文章!

标签:PHP__destruct()