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.

Bookmark and Share

Somewhat related posts

3 Responses to “Redefine $this?”

  1. Stoyan Says:

    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 ;)

  2. ali masoudi Says:

    $this=null every time doesnt work. i need somwhere to redefine a class . i designed a module algorithm in my mind and need to it and see this
    http://php.morva.net/manual/en/language.oop.php#52229

Leave a Reply