What’s $this?

August 31st, 2006. Tagged: PHP certification

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

class a {
    function aa(){

class b {
    function bb(){

$b_obj = new b;

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

Tell your friends about this post: Facebook, Twitter, Google+

6 Responses

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

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

  3. $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. ShaymoL is right. if we do the reverse i.e if we create object of class a and call b, like the code below,


    the answer will be a and not b.

  5. 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
    specially the “::” marks.

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


Leave a Reply