views:

85

answers:

2

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 is permanently gone?

+1  A: 

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.

CaseySoftware
+1  A: 

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();
Artefacto