PHP5 Tutorial - $this variable explained

$this variable is a pointer to the object making the function call. $this variable is not avialable in static methods. We will learn more about static methods in the next series of tutorials.





Example:

class Customer {
 
   private $name;
 
   public setName($name) {
	$this->name = $name;
   }
 
}
 
$c1 = new Customer();
$c2 = new Customer();
 
$c1->setName(“Sunil”);
$c2->setName(“Vishal”);

In the above example, $c1 and $c2 are two separate Customer objects. Each object has its own memory to store names. But if you see the function setName() is common. During run time, how can it make a difference as to which memory location to use to store the function values. Therefore, it uses the $this variable. As mentioned earlier, $this variable is a pointer to the object making a function call. Therefore when we execute $c1->setName(”Sunil”), $this in the setName() function is a pointer or a reference to the $c1 variable.

Related Posts on PHP5 Tutorial - Object Oriented Programming (OOPS)

  1. PHP5 Tutorial - Learn to create a PHP5 Class
  2. PHP5 Tutorial - Learn to Create a PHP5 Class Object
  3. PHP5 Tutorial - Defining Attributes of a PHP5 Class
  4. PHP5 Tutorial - Defining Methods of a PHP5 Class
  5. PHP5 Tutorial - Creating a PHP5 Constructor __construct()
  6. PHP5 Tutorial OOPS - Creating a PHP5 Destructor __destruct()
  7. PHP5 Tutorial OOPS - PHP5 Class Access Specifiers - public, private and protected
  8. PHP5 Tutorial - $this variable explained
  9. PHP5 Tutorial - instanceOf Operator Explained
  10. PHP5 Tutorial - Magic Methods - __toString() method
  11. PHP5 Tutorial - Magic Methods - __get() and __set()
  12. PHP5 Tutorial - Magic Methods - __isset() and __unset()
  13. PHP5 Tutorial - Magic Methods - __call() method
  14. PHP5 Tutorial - Magic Methods - __autoload() method
  15. PHP5 Tutorial - Magic Methods - __sleep() and __wakeup()
  16. PHP5 Tutorial - Magic Methods - __clone() method




del.icio.us Reddit Slashdot Digg Facebook Technorati Google StumbleUpon Windows Live Furl Netscape Yahoo Bloglines Bookmark.it Ask Spurl Diigo

One Response to “PHP5 Tutorial - $this variable explained”

  1. its very awesome,fantastic,amazing and …. and ……

Leave a Reply

Top Internet blogs Programming Blogs - Blog Catalog Blog Directory TopOfBlogs Technology blogs Top Blog Topsites List