When $this is Available in a Class

There are some cases when you will find that $this is not available inside a class. When the object of a class is defined immediately the $this becomes available. But when a class method is directly called through the class name then $this is not available.

See the code segment below:


class User
{   
   public function checkClass()
   {
      $msg = "\$this is not defined.\n";
      if(isset($this)) 
      {
         $msg = "\$this is defined (" . get_class($this) . ")\n";
      } 
      echo $msg; 
   }
}
Now, for the above class if checkClass method is called by instantiating the object then $this becomes available.
$userObject = new User(); 
$userObject->checkClass();
But if the above class is called using the class name like below then the $this is not available inside the class.
User::checkClass();

Comments