Posted by: phillipnb | February 27, 2011

$this and php class 


When you write a class in php the most frequently used keyword is “$this”.The author of the class is forced to access some variable or a function from some part of the class and this access is possible due to the keyword called $this.If somebody were to question you about the definition of $this, you can boldly say that it refers to the current object. Current object in the sense that what ever object (or current instance of the class) you are dealing with right now inside a class. The next question that can be asked here will be, “Why do we need a keyword like $this”? This answer to this is, “Function and Variables within a class needs an object context,some sort of handle to access them”. $this keyword provides exactly this sort of object context, a dedicated and accepted handle to access the class’s functions and variables.If you had previously written and debugged a php class file you might have come across the error that php throws when you tried to access a function or a variable inside a php class just by using the function or variable name. To access a class’s variable you just don’t use the variable name alone,instead you access the variable by using the keyword $this pointing to that variable (e.g. $this->variable).

Here is an example to show the use of $this


class myClass
{
 public $myUser = 'Phillip';
 public function sayHello($myName)
 {
  echo "\n Hello $myName";
 }
 public function printHello($myName)
 {
  if (empty($myName))
  {
   echo "\n User name in this class is ".$this->myUser;
   $this->sayHello('Tom');
  }
  else
  {
   $this->sayHello($myName);
  }
 }
} // class myClass

$objMC = new myClass;
$objMC->sayHello($objMC->myUser);
$objMC->printHello('');

Till next time, keep playing with $this – Happy PHPing!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: