Redefine $this?
I was wondering - can you redefine the special variable $this when in a method of a class. It turns out that yes, you can.
Consider this class:
< ?php
class Some {
function Some(){}
function another(){
$this = 5;
var_dump($this);
}
}
?>
If you create an object and call the another() method, it will redefine $this and will make it an integer as opposed to an object.
< ?php
$s = new Some();
$s->another();
?>
This gives
int(5)
If you dump the instance after the method call it will still return 5, so it's not just a temporary re-definition.
Similarly, you can even destroy an object from within a method of the class, like
< ?php
class Some {
function Some(){}
function another(){
$this = null;
}
}
$s = new Some();
$s->another();
var_dump($s);
?>
This will output NULL.
This entry was posted on Monday, March 28th, 2005 and is filed under PHP certification. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

May 20th, 2005 at 1:47 pm
This is true only for PHP versions < 5.
In PHP 5 an error will occur saying that you cannot re-assign $this.
Anyway, I doubt that such questions will be asked during the exam and in the real life thou shall restrain the temptation to settling for such hacky stunts, it just looks wrong
October 24th, 2005 at 3:31 am
$this=nullevery time doesnt work. i need somwhere to redefine a class . i designed a module algorithm in my mind and need to it and see thishttp://php.morva.net/manual/en/language.oop.php#52229
September 19th, 2012 at 9:36 am
That’s a knowing answer to a dfificlut question