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?

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.