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) { }

Bookmark and Share

Somewhat related posts

5 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.

Leave a Reply