0

I'm having a hard time understanding the pseudo variable $this. Take for example the following code:

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

$a = new A();
$a->foo();
A::foo();
?>

It will output:

$this is defined (A)
$this is not defined.

OK, this output makes sense to me, since $a->foo refers to an instance and A::foo refers to a class without an instantiation. But take this other example, if we append the following code to the first example:

<?php
class B
{
    function bar()
    {
        A::foo();
    }
}

$b = new B();
$b->bar();
B::bar();
?>

It will output this:

$this is defined (B)
$this is not defined.

I can understand the second output, because B::bar(); refers to a class, not an instance. But I don't get the first output. Why is $this instantiated if the method calls A::foo();, which is a class and should not be instantiated, and even worse, why would $this be an instance of B and not of A?

Thanks for your attention!

renatov
  • 5,005
  • 6
  • 31
  • 38

2 Answers2

3

$this refers to your current object. So it has no relation to what you call inside your bar() method. And since you are creating object of B ($b = new B();) so you are getting the output as $this is defined (B)

This POST will give you better idea of $this and self as well

Community
  • 1
  • 1
pratim_b
  • 1,160
  • 10
  • 29
1

By instantiating B you are setting $this to be that instance of B.

Since A::foo() echoes $this if it's defined (which it is since your calling A::foo() inside an instance of B) you see A::foo() echoing the B instance.

$b = new B() // any member function of B has $this defined now.

$b->bar() // member function of B, $this is defined. A::foo() will echo B's instance of $this

A::foo() // no class instantiation, $this is not defined

B::bar() // no class instantiated, $this is not defined as you pointed out earlier.
PandemoniumSyndicate
  • 2,855
  • 6
  • 29
  • 49
  • I understand it know, even though A::foo() is a static method, b instance is the one who's calling it, so the pseudo variable $this is defined. Thank you very much! – renatov Feb 08 '14 at 01:53