I came across one class and what cought my attention right away was this:
public function __destruct() {
unset($this);
}
My first thought was that this is just plain stupidity, it fact it looked so idiotic that I thought that either there really i开发者_运维问答s a good reason to do this or the author is just clueless
Any thoughts? Any reasons to do this?
Short answer: No
Long answer: Noooooooooooooooooooooo
My first thought was that this is just plain stupidity, it fact it looked so idiotic that I thought that either there really is a good reason to do this or the author is just clueless.
The latter, I'm afraid: there is no point in unsetting an instance on destruct. It might be the original programmer is a big fan of being explicit, but the worst thing is that this doesn't even work:
<?php
class Foo {
function __destruct( ) {
unset( $this );
}
}
$foo = new Foo;
$foo->__destruct( );
var_dump( $foo );
Given that the destructor is only invoked on an unset($object)
or garbage collection of unreferenced objects, the usefulness of an inner unset($this)
is quite self explanatory.
In particular it will have no effect itself, because it only clears the name reference $this
. It does not free the occupied memory, which happens after the destructor is left.
In contrast it is sometimes sensible to use:
unset($this->subobject);
Which is probably what the author here misremembered and misapplied.
No real point that I can think of. Maybe ask the developer about it.
I can't see the point of this, considering the triggers for the __destruct method to be called. From http://www.php.net/manual/en/language.oop5.decon.php:
The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.
Also note that it probably wouldn'd do what you expect even if the __destruct method was called manually. From http://php.net/manual/en/function.unset.php:
It is not possible to unset $this inside an object method since PHP 5.
Some testing reveals that all this will do is remove the current $this reference to the object within the __destruct method.
Found this on the internet.
unset($this) will only remove $this from variable space of the current function scope. The object will remain in the caller scope.
You can do a $this = null to overwrite the object however.
http://bytes.com/topic/php/answers/459538-oop-unset-maybe-unset#post1762212
精彩评论