Entry
Can I make an assignment to $this in a class method?
How can I reset or clear the value of an object?
Jun 30th, 1999 20:20
Nathan Wallace, Ben Udall, Mark, Steve Dicks
The complete '$this' pointer should be considered read-only in methods
(you are attempting to overwrite yourself, never a good thing). If you
tried this is any other language it is unlikely to work either.
Here is an example where the clear() method will cause problems in PHP:
class Ob {
var $i = 1;
function set_i ($a) { $this->i = $a; }
function clear () { $this = new Ob; }
}
If you want to clear an object, or any case where you might be tempted
to assign a value to the $this pointer, you should just set the values
of the variables contained in the $this object.
So the correct solution for the bad class example above is:
class Ob {
var $i = 1;
function set_i ($a) { $this->i = $a; }
function clear () { $this->i = 1 }
}