tags:

views:

48

answers:

3

After taking a look at some old code:

//Nothing like a destructor!!
function destroy() {
    settype(&$this, 'null');
}

And called by

$Cache->destroy();

However in PHP 5.3 I get Deprecated: Call-time pass-by-reference has been deprecated in /blah/-cache-.php on line 154

How should I do this?

+2  A: 

Just destroy the object like normal.

unset($Cache);

I don't know why they would do that nasty looking mess above. Keep in mind that if the object has pointers in different places you will need to unset all of them - not just that one line. (singletons are an example)

Xeoncross
+8  A: 

Your immediate problem can be met by removing the & in $this, but the whole construction doesn't make sense to me. If it's not plain invalid to destroy $this from within the object's context, it's definitely not good practice.

To destroy an object, a simple

unset($Cache);

will do.

If one wants to execute stuff when the object is destroyed, one should define a destructor in the class. (The comment in your destroy() code says that this is not the point here, though. :)

Pekka
+1  A: 

The error you're getting is not related to having a destructor. The error is simply because you've tried to pass $this by reference in a function call.

PHP used to allow this, but in current versions of PHP, if you want to pass something by reference, you should specify it in the function declaration.

Therefore, your function call should look like this:

settype($this, 'null');

(ie without the &). (btw -- the word 'null' in a string??? is that what you meant?)

And if you want to pass by ref, your function should look like this:

function settype(&$object, $secondparameter) {
    ...whatever the function does...
}

ie with the & in the function parameter.

This rule applies in all cases in PHP. As I said, it has nothing to do with your destructor method, or with it being an object; that's just how you pass by reference in modern PHP.

Now onto the other part of your question: A destructor method.

PHP does allow for an automatic destructor function, written within your class like this:

function __destruct() {
    print "Destroying " . $this->name . "\n";
}

If you write this code, the __destruct() method will be called when the object is destroyed. This may or may not be what you want -- depends on how you want it to work. The object will be destroyed when all references to it are unset or come out of scope. If you're passing the object handle around by reference, this may not happen when you expect it to -- ie the object may persist in memory even when you say unset($myobject);. In this case, it may only actually get destroyed when the PHP program finishes running. If this is the case, and you need it to be called sooner than that, you may be fine continuing with the destroy() method you have already, and calling it explicity.

Hope that answers your question.

Spudley
+1 for explaining the background of the error message
Pekka