I've made a class that acts like an file wrapper. When user call delete method, i want to unset the object (actually $this). Is there a way (workaround) to do that? The manual said no, there is no way...
The manual is right. There is no way.
unset
is used essentially to say "I'm finished using a particular variable; it can be considered for garbage collection as far as I'm concerned.
The trouble is that $this
only makes sense in the context of a method call anyway. Once the method completes, $this
will fall out of scope (essentially) and will no longer count as a reference to the object. (For practical purposes.)
So you don't need to worry about freeing up $this
. PHP will take care of that.
What you're probably trying to do is unset
the other variables that might reference the same instance. And unless you have access to those from within the method, you can't touch them, much less unset
them.
As far as I know, there is no way to destroy a class instance from within the class itself. You'll have to unset the instance within its scope.
$myClass = new fooBar();
unset($myClass);
Somewhat related: Doing the above will automatically call any existing __destruct()
magic method of the class so you can do any additional cleanup. More info
I spent a lot of time finding a way of setting to NULL an object from within it's self.
Please try this code:
<?php
class bike{
public $color = "black";
function destroySelf(bike &$me){
$me = NULL;
//$me = new bike();
}
}
$iRide = new bike();
$iRide->color = "red";
var_dump($iRide);echo " -before <br>";
$iRide->destroySelf($iRide);
var_dump($iRide);echo " -after <br>";
?>
Trick is $this won't work, you need to pass it the actual reference by reference to the class.
Another way to access the actual reference without passing it is defining the object as a global:
class bike{
public $color = "black";
function destroySelf(){
global $iRide;
$iRide = NULL;
//$iRide = new bike();
}
}
$iRide = new bike();
$iRide->color = "red";
var_dump($iRide);echo " -before <br>";
$iRide->destroySelf();
var_dump($iRide);echo " -after <br>";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With