dsxay48646 2013-02-06 15:44
浏览 50

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

I have found this solution, but perhaps there is a better one, what do you think about it?

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;

If I use the class A as-is, then unsetting doesn't work because A has a self-reference in one of its property.

In this case I need to manually call the garbage collector.

The solution I have found is to use a proxy class, called AProxy, which calls a special function named myDestructor in A which only destruct the A class and not its parent.

Then the destructor of AProxy calls myDestructor on the instance of A.

In order to make AProxy resemble the A class, I reimplemented the __call function (the setters and getters for properties may also be overloaded).

Do you have a better solution than that?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测