Logo

$this variable

Posted under » PHP » OOP on 13 March 2009

$this variable in object-oriented language

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

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

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();

The above example will output:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

Page 1 : OOP Introduction

Page 2 : Using classes and objects

Page 3 : Implementing a Simple Class in PHP