What’s $this?

Simple question, what's $this - a or b?

<?php
class a {
    function aa(){
        var_dump($this);
    }

}

class b {
    function bb(){
        a::aa();
    }

}

$b_obj = new b;
$b_obj->bb();
?>

Answer: object(b)#1 (0) { }

This entry was posted on Thursday, August 31st, 2006 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

6 Responses to “What’s $this?”

  1. rajesh Says:

    Althoug code is very small, but thats sufficient to explain the meaning of $this. I loved it.
    Thanks for a brainy posting.

  2. mohammed Alkhateeb Says:

    the answer is a , because $this that mean this is to this class

  3. ShaymoL Says:

    $this always is a reference to the calling object
    In your code as $b_obj object is calling bb() method of class b , so the output will be class b

  4. subh Says:

    ShaymoL is right. if we do the reverse i.e if we create object of class a and call b, like the code below,

    aa();
    ?>

    the answer will be a and not b.

  5. Muhammad Says:

    it will give this output
    object(b)#1 (0) { }

    but if you ask what $this-> it refer for a, cause it refer for it’s class
    but i don’t know what this line mean
    a::aa();
    specially the “::” marks.

  6. Alex Says:

    @Muhammad when ‘::’ is used this means we call static
    function/method of a class without instantiating it.

    Cheers
    Alex

Leave a Reply