开发者

Calling Destructor within Object Method in PHP

I have an object that can be used, or eaten, or whatnot in PHP. In any case, it ends up gone. I have an abstract protected method called activate(), which is called by a public method useItem().

Is it possible for useItem() to destroy itself after calling activate()? If not, what is the best way of making sure the item开发者_JAVA技巧 is permanently gone?


If I understand correctly you have something like:

class AbstractMyClass {
    abstract protected function activate();
    public function useItem() {
        //...
        $this->activate();
        //...
    }
}

class MyClass extends AbstractMyClass { /* ... */ }

In this case, no, there's no way to make the object being destructed after calling useItem short of:

$obj = new MyClass();
$obj->useItem();
unset($obj);
//if there are cyclic references, the object won't be destroyed except
//in PHP 5.3 if the garbage collector is called

Of course, you could encapsulate the destroyable object in another one:

class MyClass extends AbstractMyClass { /* ... */ }
class MyWrapper {
    private $inner;
    public function __construct($object) {
        $this->inner = $object;
    }
    public function useItem() {
        if ($this->inner === null)
            throw new InvalidStateException();
        $this->inner->useItem();
        $this->inner = null;
    }
}

$obj = new MyWrapper(new MyClass());
$obj->useItem();


You can simply unset() it if you wish.

Realistically, the garbage collector or GC in PHP will do all the work you need once the variable goes out of scope or there are zero references to it. To be clear, the GC got a major rework in PHP 5.3, so if you're using 5.2.x, you may still have some performance issues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜