如何取消设置包含自引用的对象?

时间:2013-02-06 15:44:44

标签: php destructor self-reference

我找到了这个解决方案,但也许有一个更好的解决方案,你怎么看?

class A
{
        #A self-reference
        private $_a;
        #Construcotr makes a self-reference
        public function __construct()
        {
                $this->_a = $this;
        }
        #Some other functions
        public function hello()
        {
                echo 'Hello, world!' . PHP_EOL;
        }
        #Function to destruct just this object, not its parent
        public function myDestruct()
        {
                unset($this->_a);
                var_dump($this);
        }
}

class AProxy
{
        #The proxied object
        public $_a;
        #The constructor has to be rewritten
        public function __construct()
        {
                $this->_a = new A();
        }
        #The destructor
        public function __destruct()
        {
                $this->_a->myDestruct();
                unset($this->_a);
                var_dump($this);
        }
        #Some other functions
        public function __call($fct, $args)
        {
                call_user_func(array($this->_a, $fct), $args);
        }
}

echo 'START' . PHP_EOL;
#Use class AProxy instead of class A
$a = new AProxy();

$a->hello();

unset($a);

#Otherwize you need to trigger the garbage collector yourself
echo 'COLLECT' . PHP_EOL;
gc_collect_cycles();

echo 'END' . PHP_EOL;

如果我按原样使用A类,那么取消设置不起作用,因为A在其中一个属性中有自引用。

在这种情况下,我需要手动调用垃圾收集器。

我找到的解决方案是使用一个名为AProxy的代理类,它在A中调用一个名为myDestructor的特殊函数,它只破坏A类而不是它的父类。

然后,AProxy的析构函数在A的实例上调用myDestructor。

为了使AProxy类似于A类,我重新实现了__call函数(属性的setter和getter也可能被重载)。

你有比这更好的解决方案吗?

0 个答案:

没有答案